element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Code Exchange
  • Technologies
  • More
Code Exchange
Blog modern C++: write my own function that returns true / false, and a value or error message
  • Blog
  • Forum
  • Documents
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Code Exchange to participate - click to join for free!
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: Jan Cumps
  • Date Created: 1 Mar 2025 10:29 PM Date Created
  • Views 461 views
  • Likes 3 likes
  • Comments 2 comments
  • gcc
  • Modern C++
  • c++26
  • gcc15
  • c++
Related
Recommended

modern C++: write my own function that returns true / false, and a value or error message

Jan Cumps
Jan Cumps
1 Mar 2025

I'm experimenting with new C++ constructs. GCC 15 implements an interesting concept of the C++26 standard: A function can return a status, and either a value or an error message. In a previous post I tested one of C++ standard functions that uses this. Now I'm trying to write one myself.

What does the example do?

I made a mock function that pretends it gets GPS coordinates from a satellite. It is always possible that there aren't enough satellites in view, so this call can fail.
Because this is a mock, I let it fail if you pass false to its succeed parameter. And I let it succeed if that parameter is true. Its only purpose is to let me show this new C++ mechanism.

  • if the function succeeds, it returns true, and coordinates in return variable coord.
  • if the function fails (no satellites in view Slight smile), it returns false, and an error code in return variable ec.

image

Code of a function that applies this mechanism

I created a class to contain the coordinates, and specific to this new mechanism, a class that can hold return variables and report status.

struct coordinate {
	float lat;
	float lon;
};

struct gps_coord_result {
    coordinate coord;
    std::errc ec;
    constexpr explicit operator bool() const noexcept { return ec == std::errc{}; }
};

In that second definition, struct gps_coord_result, you can already see the mechanism unfolding. It can hold the coordinates and error message. And it knows how to generate the true or false reply based on its content.

Now the function that applies this mechanism:

// mock function pretends it gets gps coordinates from a satellite
// and that can be asked to fail :)
gps_coord_result get_gps_coordinates(bool succeed) {
    if (succeed) {// return a valid coordinate :)
        return { coordinate{1.1, 2.2}, std::errc{} };
    } else { // our gizmo failed to get satellite feedback
        return { coordinate{}, std::errc::timed_out };
    }
}

If the mock connection with the satellite succeeds, we create a gps_coord_result object and set the coordinates we received from our gps. And set an empty error message.
If the communication fails, we create a gps_coord_result object and set the error field.
in both cases we return that  gps_coord_result object.

Test bed

Now a function that calls our function, and acts on the results:

void process_coordinates(bool succeed) {
	if (auto [coord, ec] = get_gps_coordinates(succeed)) {
        std::cout << "lat: " << coord.lat << ", lon: " << coord.lon << std::endl;
	} else {
        std::cout << std::make_error_code(ec).message() << std::endl;
	}
}

It calls gps_coord_result() and captures the return variables coord and ec. Based on the return value, it either processes the coordinates, or prints the error.

And in main, I call this function twice. Once to test the success scenario, once for failure:

int main() {
	process_coordinates(true);
	process_coordinates(false);
}

Results:

lat: 1.1, lon: 2.2
Connection timed out

Thank you for reading.

reference: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p0963r3.html

  • Sign in to reply
  • Jan Cumps
    Jan Cumps 6 months ago in reply to vmate

    Yes, this c++ feature (and several others that made it to the standards) is also inspired on rust. 

    Majority of what I wrote above was already available in GCC 14. 
    The new thing (not new in the standard, but new in GCC: capability "_cpp_structured_bindings >= 202406L"), is that you now can capture the return variables:

    if (auto [coord, ec] = get_gps_coordinates()) // ...

    In GCC14, you had a little more work:

    if (auto result = get_gps_coordinates()) // ...

    then get at the return variables as result.coord and result.ec .

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • vmate
    vmate 6 months ago

    Check out `expected` in C++23, it is very similar to rust's `Result` type, made specifically for what you're trying to do.
    en.cppreference.com/.../expected

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube