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 ?