C++17 optional

optional的作用

类模板 std::optional 管理一个可选的容纳值,即可以存在也可以不存在的值

一种常见的 optional 使用情况是一个可能失败的函数的返回值。与其他手段,如 std::pair<T,bool> 相比, optional 良好地处理构造开销高昂的对象,并更加可读,因为它显式表达意图。

示例

/** @file  optionalT.cpp
*  @note   All Right Reserved.
*  @brief
*  @author xor
*  @date   2019-11-2
*  @note   
*  @history
*  @warning
*/
#include <string>
#include <functional>
#include <iostream>
//#include <optional>
#include <experimental/optional>//试验阶段
using namespace std;
// optional 可用作可能失败的工厂的返回类型
std::optional<std::string> create(bool b) {
    if(b)
        return "Godzilla";
    else
        return {};
}

// 能用 std::nullopt 创建任何(空的) std::optional
auto create2(bool b) {
    return b ? std::optional<std::string>{"Godzilla"} : std::nullopt;
}

// std::reference_wrapper 可用于返回引用
auto create_ref(bool b) {
    static std::string value = "Godzilla";
    return b ? std::optional<std::reference_wrapper<std::string>>{value}
             : std::nullopt;
}

int main()
{
    std::cout << "create(false) returned "
              << create(false).value_or("empty") << '\n';

    // 返回 optional 的工厂函数可用作 while 和 if 的条件
    if (auto str = create2(true)) {
        std::cout << "create2(true) returned " << *str << '\n';
    }

    if (auto str = create_ref(true)) {
        // 用 get() 访问 reference_wrapper 的值
        std::cout << "create_ref(true) returned " << str->get() << '\n';
        str->get() = "Mothra";
        std::cout << "modifying it changed it to " << str->get() << '\n';
    }
}

猜你喜欢

转载自www.cnblogs.com/guxuanqing/p/11783069.html