[英]C++17 Tuple Unpacking
I am trying to unpack a tuple and use the results to assign into members. 我试图打开一个元组,并使用结果分配给成员。 Is it possible to do that in idiomatic C++17?
是否可以在惯用的C ++ 17中做到这一点?
I realize that std::tie
exists but I am trying to utilize C++17 features and not default to older features nor the old way ( std::get<N>(tuple)
) 我意识到存在
std::tie
,但是我正在尝试利用C ++ 17功能,而不是默认使用旧功能或旧方法( std::get<N>(tuple)
)
tuple<A, vector<A>> IO(){
//IO happens here
return {var, vec};
}
class foo{
public:
foo();
private:
A var;
vector<A> vec;
};
foo::foo(){
//this line here: I want to assign var and vec from IO()
[var, vec] = IO();
}
Not really. 并不是的。 Structured bindings can only declare new names, it cannot assign to existing ones.
结构化绑定只能声明新名称,而不能分配给现有名称。
Best would be to just do this: 最好是这样做:
foo() : foo(IO()) { } // delegate to a constructor, calling IO
foo(std::tuple<A, vector<A>>&& tup) // manually unpack within this constructor
: var(std::get<0>(std::move(tup)))
, vec(std::get<1>(std::move(tup)))
{ }
If A
happens to be default constructible and move assignable, then yeah this works too: 如果
A
恰好是默认可构造且可移动的,那么是的,它也可以工作:
foo() {
std::tie(var, vec) = IO();
}
If A
happens to not be default constructible, then you could use optional
to add that extra state: 如果
A
碰巧不是默认可构造的,则可以使用optional
添加该额外状态:
struct foo {
std::optional<A> var;
std::vector<A> vec;
foo() {
std::tie(var, vec) = IO();
}
};
None of these are particularly great. 这些都不是特别出色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.