返回带有 ?: 运算符的可选值
Return Optional value with ?: operator
我经常需要对函数使用可选类型:
std::optional<int32_t> get(const std::string& field)
{
auto it = map.find(field);
if (it != map.end()) return it->second;
return {};
}
有没有办法在一行中返回可选值?例如:
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
。
std::nullopt
:
std::nullopt
是std::nullopt_t
类型的常量,用于 指示具有未初始化状态的可选类型。。
std::nullopt_t
:
std::nullopt_t
是用于指示可选类型的空类类型 具有未初始化状态。特别是,std::optional
有一个 构造函数,nullopt_t
作为单个参数,这将创建一个 不包含值的可选。
使用这种方法,三元运算符调用的 true 子句显式返回具有 some-value 的std::optional
,因此编译器可以从提供的包装值的类型推断模板参数/包装类型(在此示例中:int32_t
(,这意味着您无需显式指定它。
应用于您的示例:
return it != map.end() ? std::optional(it->second) : std::nullopt;
// alternatively
return it != map.end() ? std::make_optional(it->second) : std::nullopt;
return it != map.end() ? it->second : std::optional<int32_t>{};
应该做这个伎俩。
编译器必须从最后两个操作数中推断出三元表达式的结果类型,但它无法从int32_t
和{}
中推断出std::optional<int32_t>
。
另一方面,int32_t
和std::optional<int32_t>
确实具有所需的通用类型std::optional<int32_t>
。
相关有趣的事实:您可以通过自动返回类型扣除来避免重复类型:
auto get(const std::string& field)
{
auto it = map.find(field);
return it != map.end() ? it->second : std::optional<int32_t>{};
}
根据偏好,您当然也可以从decltype
it->second
中推断std::optional
的模板参数,以进一步减少重复。
相关文章:
- 重载更少,则运算符返回相反的布尔值
- 使用重载 [] 运算符返回 std::map() 的可赋值
- 为什么我的超载"+"运算符返回的总额错误?
- (C++)为什么"||"逻辑运算符返回 1?
- 为流运算符返回代理类时解压缩参数
- C++ 运算符返回差异
- 重载运算符返回什么类型的值(对于用户定义的类型):右值还是左值?
- 运算符返回的指针的有效性 >
- 字符串流运算符>>返回值
- 动态指针引用数组由三元运算符返回值,但有异常
- 重载运算符返回的对象正在丢失 C++ 中的数据
- 如何使用设置运算符返回非 const 对象>
- 重载常量和非常量转换运算符返回数组类型时出现 MSVC 错误 C2593
- 为什么比较运算符"=="返回"YES"即使两个向量不同?
- 如何从重载的下标 [] 运算符返回 std::unique_ptr&?
- 从重载运算符返回对象>>
- 获取对运算符 [] 返回值unordered_map引用
- 我无法让这个虚拟模板化函子运算符返回正确的类型
- 为什么迭代器运算符 + 返回副本
- 从运算符[]返回对映射的char*的引用