We can return a tuple
std::pair<bool, std::string> fooFunction();
but that makes code redundant when creating the return value , and force callers to handle the tuple (easy with structural binding in c++17)
if ( okayCondition)
return {true, {}};
else
return { false, "blabla error"};
or we can use
std::optional<std::string> fooFunction();
Which is interesting for existing functions returning bool because mostly the callers would not need update thanks to the std::optional operator bool
//Legacy code ok
if (fooFunction())
I am aware of an heavier approach, a templated ReturnStatus class that throws in case the caller does not test the return status value.
Is there any other approach ?
You could consider returning a std::error_code
from your function.
Using this class you can provide a std::error_code::value
which you can use for error handling and a std::error_code::message
to display info to the user if there is anything actionable or informative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With