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
), it returns false, and an error code in return variable ec.
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