码迷,mamicode.com
首页 > 编程语言 > 详细

C++17 optional

时间:2019-11-02 17:41:10      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:hang   get   ges   管理   一个   else   函数   reserve   util   

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;
    }
}

 

C++17 optional

标签:hang   get   ges   管理   一个   else   函数   reserve   util   

原文地址:https://www.cnblogs.com/guxuanqing/p/11783069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!