Best alternative to std::optional to return an optional value from a method? (using C++98/C++11/C++14)

こ雲淡風輕ζ 提交于 2019-12-21 03:14:07

问题


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:

  1. 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
  2. Pairing it up with a bool

    std::pair<double,bool> possiblyFailingCalculation();
    
  3. Old style

    bool possiblyFailingCalculation(double& output);
    
    • (−) incompatible with new C++11 auto value = calculation() style
  4. 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 ?

  5. Throw an exception

    • (−) Sometimes "impossible to calculate" is a valid return value.

回答1:


std::optional, like its boost::optional parent, is a pretty basic class template. It's a bool, some storage, and a bunch of convenience member functions most of which are one line of code and an assert.

The DIY option is definitely preferred. (1) involves allocation and (2), (3) involve having to construct a T even if you want a null value - which doesn't matter at all for double but does matter for more expensive types. With (5), exceptions are not a replacement for optional.

You can always compare your implementation to Boost's. It's a small header-only library, after all.




回答2:


Return a struct (or a class if you want portable cast operators)



来源:https://stackoverflow.com/questions/36033337/best-alternative-to-stdoptional-to-return-an-optional-value-from-a-method-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!