structured binding of member variables

纵饮孤独 提交于 2021-02-05 07:52:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!