成员变量的结构化绑定 [英] structured binding of member variables
问题描述
在Visual Studio 2017中,打开/std:c ++ 17
后,我可以做
In visual studio 2017, after turning on /std:c++17
, I can do
auto [d1, d2] = func_return_tuple();
,其中 func_return_tuple()
返回两个双精度值的元组.
, where func_return_tuple()
returns a tuple of two double value.
但是,如果类A有两个成员变量 d1 _
和 d2 _
,我就不能这样做
However, if class A has two member variable d1_
and d2_
, I can't do
A a;
auto [a.d1_, a.d2_] = func_return_tuple();
有没有出路?
当然
std::tie(a.d1_, a.d2_) = func_return_tuple();
始终有效.
推荐答案
有没有出路?
基本上,不.结构化绑定仅与将对象分解为组成元素有关.它总是引入 n 个新名称-每个元素一个.您不能通过结构化绑定进行分配,也不能使用它来重新绑定现有名称或类似名称.
Basically, no. Structured bindings is only about decomposing an object into constituent elements. It always introduces n new names - one for each element. You cannot assign through a structured binding, nor can you use it to rebind existing names, or anything like that.
您的选择基本上是:
std::tie(a.d1_, a.d2_) = func_return_tuple();
或者,假设 A
是包含这两个成员的聚合,例如:
Or, assuming A
is an aggregate containing those two members, something like:
template <typename T>
struct list_init_t {
template <typename... Args>
T operator()(Args&&... args) const {
return T{std::forward<Args>(args)...};
}
};
template <typename T>
inline constexpr list_init_t<T> list_init;
用作:
a = std::apply(list_init<A>, func_return_tuple());
这篇关于成员变量的结构化绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!