Boost C++ 库

世界上最受推崇、设计最精良的 C++ 库项目之一。 Herb SutterAndrei Alexandrescu, C++ Coding Standards

Boost.Optional - Boost C++ 函数库
Next

Boost.Optional

Fernando Luis Cacciola Carballal

根据 Boost 软件许可证版本 1.0 发布。(参见随附文件 LICENSE_1_0.txt 或在 https://boost.ac.cn/LICENSE_1_0.txt 复制)

类模板 optional 是一个包装器,用于表示可能(尚未)包含有效值的“可选”(或“可空”)对象。可选对象提供完整的价值语义;它们适用于按值传递和在 STL 容器内使用。这是一个仅限头的 C++11 库。

问题

假设我们要从配置文件中读取一个表示某个整数值的参数,我们称之为 "MaxValue"。该参数可能未指定;这种情况并非错误。未指定该参数是有效的,在这种情况下,程序应表现得略有不同。另外,假设 int 类型的任何可能值都是 "MaxValue" 的有效值,因此我们不能仅使用 -1 来表示配置文件中缺少该参数。

解决方案

使用 boost::optional 的解决方法如下:

#include <boost/optional.hpp>

boost::optional<int> getConfigParam(std::string name);  // return either an int or a `not-an-int`

int main()
{
  if (boost::optional<int> oi = getConfigParam("MaxValue")) // did I get a real int?
    runWithMax(*oi);                                        // use my int
  else
    runWithNoMax();
}

Next