【发布时间】:2018-04-07 06:06:40
【问题描述】:
我想从另一个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);
}
【问题讨论】:
-
val{ oi ? decltype(val){{*oi, f, c}} : std::nullopt }? -
@zneak 是的,它会起作用,但我们可以摆脱
decltype吗? -
Typedef 呢?我认为你的双手被类型推断在这里的工作方式束缚了。
-
处理这个问题的“真正惯用”方法是让
flat_map函数与std::optional一起使用,但我认为没有标准函数。 -
std::tuple{*oi, f, c}可能比decltype更清晰,尽管它们并不完全相同。