Obviously, std::optional
is the best choice to return an optional value from a function if one uses C++17 or boost (see also GOTW #90)
std::optional<double> possiblyFailingCalculation()
But what and why would be the best alternative if one is stuck with an older version (and can't use boost)?
I see a few options:
STL smart pointers (C++11 only)
std::unique_ptr<double> possiblyFailingCalculation();
- (+) virtually the same usage as optional
- (−) confusing to have smart pointers to non-polymorphic types or built-in types
Pairing it up with a bool
std::pair<double,bool> possiblyFailingCalculation();
Old style
bool possiblyFailingCalculation(double& output);
- (−) incompatible with new C++11
auto value = calculation()
style
- (−) incompatible with new C++11
A DIY template: a basic template with the same functionality is easy enough to code, but are there any pitfalls to implement a robust
std::optional<T>
look-a-like template ?Throw an exception
- (−) Sometimes "impossible to calculate" is a valid return value.