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.
Example is the standard std::to_chars() function. It will return a bool that reports success or failure, and it returns either the result, or error info.
Here is an example of how to use it:
std::array<char, 5> str; if (auto [ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), value)) std::cout << std::string_view(str.data(), ptr) << '\n'; else std::cout << std::make_error_code(ec).message() << '\n';
The function std::to_chars() returns true if successful, falls if failed, and you can get at the relevant response. We pass it a numerical value. If successful, ptr points to the string representation of the passed value. If it failed (e.g. because the string representation does not fit in the buffer), ec contains a std::errc object that holds error information.
What's in it for us?
This can result in code that's easier to follow. An alternative to the style where error and result are passed via parameters. In traditional C++, you can either return a status flag, an "error value", or the "business value". The others would have to be writeable parameters (a reference or pointer).
With this new capability, the parameters are all inputs, and anything the function wants to report back, is part of the return value.
Discuss