从另一个 std::optional 和其他东西初始化 std::optional 的惯用方法
Idiomatic way to initialise std::optional from another std::optional and something else
我想初始化另一个std::optional
的std::optional
和一些额外的参数,前提是后一个std::optional
不为空。不幸的是std::optional::optional
4)和5)不适合,因为参数的数量不同。
我能够想出以下内容,但仍然感觉过分。我特别不喜欢显式指定 lambda 的返回类型。
有没有更好的(如更简洁和更具表现力)的方式来实现这一目标?
#include <iostream>
#include <optional>
#include <tuple>
struct A {
A(std::optional<int> oi, float f, char c)
:
val{
[&] () -> decltype(val) /* I don't like specifying type here */ {
if (oi)
return {{*oi, f, c}};
else
return std::nullopt;
}()
}
{
}
std::optional<std::tuple<int, float, char>> val;
};
int main()
{
auto print = [](auto& r) {
if (r)
std::cout
<< std::get<0>(*r) << "; "
<< std::get<1>(*r) << "; "
<< std::get<2>(*r) << std::endl;
else
std::cout << "nullopt" << std::endl;
};
auto one = A({}, 1.0, 'c');
print(one.val);
auto two = A(10, 2.0, 'c');
print(two.val);
}
活生生的例子。
只要相信编译器会做正确的事情:
A(std::optional<int> oi, float f, char c) {
if (oi) {
val.emplace(*oi, f, c);
}
}
当然,这也是 map()
成员函数†的一个很好的用例,您可以将其编写为非成员函数:
A(std::optional<int> oi, float f, char c)
: val(map(oi, [&](int i){ return std::tuple(i, f, c); }))
{ }
<小时 />†最近由TartanLlama在P0798中提出。
相关文章:
- 检查某些类型是否是模板类 std::optional 的实例化
- 使用 std::optional,而不是自己的结构
- C++17:使用 std::optional 来评估枚举是否包含值
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- API 返回智能指针的 std::optional 以明确指定指针可能为 null 是否有意义?
- 函数可以应用于 std::optional,并返回一个可选值吗?
- 为什么 std::optional::value_or 没有默认 ctor 类型的专用化?
- 使用std::optional时的命名返回值优化
- 为什么返回std::optional有时移动,有时复制
- 为什么 std::optional 的强制转换运算符被忽略了
- C++是否在 std::min 和 std::max 下标准化 std::optional 的行为?
- std::optional - 使用 {} 或 std::nullopt 构造空
- 我可以使用 std::optional 进行错误处理吗?
- 为什么在std::optional的某些实现中有一个虚拟工会成员?
- 有什么东西阻止std::optional::value_or()有条件地不例外吗?
- 子类化 std::optional时编译错误
- 如何在构造函数中使用 std::optional
- 函数模板参数推断使用 std::Optional 失败
- 什么时候适合使用 std::optional
- 为什么 std::optional 运算符* 没有 has_value() 的调试模式断言