使用?:运算符返回可选值 [英] Return Optional value with ?: operator

查看:92
本文介绍了使用?:运算符返回可选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要对函数使用可选类型:

I often need to use optional type for functions:

std::optional<int32_t> get(const std::string& field)
{
    auto it = map.find(field);
    if (it != map.end()) return it->second;
    return {};
}

是否有一种方法可以在一行中返回可选值?例如这个:

Is there a way to return optional value in one line? e.g. this:

std::optional<int32_t> get(const std::string& field)
{
    auto it = map.find(field);
    return it != map.end() ? it->second : {};
}

导致错误

error: expected primary-expression before '{' token
return it != map.end() ? it->second : {};
                                      ^

推荐答案

您可以显式地将某些值返回值包装到std::optional中,然后回退到constexpr std::nullopt以获得无值返回值.

You can explicitly wrap the some-value return into an std::optional, and fall back on the constexpr std::nullopt for the no-value return.

std::nullopt :

std::nullopt是类型为std::nullopt_t的常量,用于 指示具有未初始化状态的可选类型.

std::nullopt is a constant of type std::nullopt_t that is used to indicate optional type with uninitialized state.

...

std::nullopt_t :

std::nullopt_t是用于指示可选类型的空类类型 处于未初始化状态.特别地,std::optional具有一个 以nullopt_t作为单个参数的构造函数,它将创建一个 可选的,不包含值.

std::nullopt_t is an empty class type used to indicate optional type with uninitialized state. In particular, std::optional has a constructor with nullopt_t as a single argument, which creates an optional that does not contain a value.

使用这种方法,三元运算符调用的true子句显式地返回带有某个值的std::optional,因此编译器可以从该类型推导模板参数/包装类型(在本示例中为int32_t)所提供的包装值的大小,这意味着您无需显式指定它.

With this approach, the true clause of the ternary operator call explicitly returns an std::optional with a some-value, so the compiler can deduce the template parameter/wrapped type (in this example: int32_t) from the type of the supplied wrapped value, meaning you needn't specify it explicitly.

应用于您的示例:

return it != map.end() ? std::optional(it->second) : std::nullopt;

// alternatively
return it != map.end() ? std::make_optional(it->second) : std::nullopt;

这篇关于使用?:运算符返回可选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆