问题
In visual studio 2017, after turning on /std:c++17
, I can do
auto [d1, d2] = func_return_tuple();
, where func_return_tuple()
returns a tuple of two double value.
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();
Is there a way out?
Of course,
std::tie(a.d1_, a.d2_) = func_return_tuple();
always works.
回答1:
Is there a way out?
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.
Your option is basically:
std::tie(a.d1_, a.d2_) = func_return_tuple();
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;
Using it as:
a = std::apply(list_init<A>, func_return_tuple());
来源:https://stackoverflow.com/questions/50962301/structured-binding-of-member-variables