Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modern C++ : what is the best approach for function returning a status (ok/not ok) and an error (if status not ok)? [closed]

Tags:

c++

c++11

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 ?

like image 617
sandwood Avatar asked Nov 26 '22 22:11

sandwood


1 Answers

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.

like image 88
Cory Kramer Avatar answered Nov 28 '22 12:11

Cory Kramer