lundi 9 novembre 2020

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

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 ?

Aucun commentaire:

Enregistrer un commentaire