本文介绍了最好的替代std :: optional从方法返回可选值? (使用C ++ 98/C ++ 11/C ++ 14)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很明显,如果使用C ++ 17或boost,std::optional是从函数返回可选值的最佳选择(另请参见 GOTW#90 )

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()

但是,如果一个人卡在一个较旧的版本中(并且不能使用boost),那又是最好的选择呢?

But what and why would be the best alternative if one is stuck with an older version (and can't use boost)?

我看到一些选择:

  1. STL智能指针(仅C ++ 11)

  1. STL smart pointers (C++11 only)

std::unique_ptr<double> possiblyFailingCalculation();

  • (+)几乎与可选的用法相同
  • (−)令人困惑地拥有指向非多态类型或内置类型的智能指针
  • 将其与bool配对

    std::pair<double,bool> possiblyFailingCalculation();
    

  • 旧样式

    bool possiblyFailingCalculation(double& output);
    

    • (−)与新的C ++ 11 auto value = calculation()样式不兼容
      • (−) incompatible with new C++11 auto value = calculation() style
      • DIY模板:具有相同功能的基本模板很容易编写代码,但是是否有陷阱实现强大的std::optional<T>外观类似模板?

        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 ?

        引发异常

        • (−)有时不可能计算"是有效的返回值.

        推荐答案

        std::optional像其boost::optional父代一样,是一个非常基本的类模板.它是一个bool,一些存储和一堆便捷成员函数,其中大多数是一行代码和一个断言.

        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.

        DIY选项绝对是首选. (1)涉及分配,(2),(3)涉及即使必须为空值也必须构造T-这对于double根本不重要,但对于更昂贵的类型确实重要.对于(5),异常不能替代optional.

        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.

        您始终可以将您的实现与Boost的实现进行比较.毕竟,这是一个很小的仅标头的库.

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

        这篇关于最好的替代std :: optional从方法返回可选值? (使用C ++ 98/C ++ 11/C ++ 14)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:23