Understand structured binding in C++17 by analogy

孤人 提交于 2019-12-01 15:54:17

It might be insightful to consider this from another perspective.

In C++ we already had variables, objects with a name int a = 5 and objects that aren't variables and do not have a name: *new int. Structured bindings are a way to have names for all parts of a variable, while the whole variable has no explicit name. So it's the combination [x,y,z] that together names an variable with three members.

Importantly, they together name an object, so the compiler actually has to layout the object. Independent variables can be placed independently on the stack. but with structured bindings the compiler cannot do so (except for the normal as-if rule)

So when we consider the combination [x y z] as the name of the variable, it's clear that auto const& [x y z] makes the combination a const& variable.

We then have to consider what exactly the individual names x, y and z mean. Your question summarizes them as

cv-auto ref-operator unique_name = ...
#define x unique_name.member_a
#define y unique_name.member_b
#define z unique_name.member_c

That's a bit tricky. Where does member_a come from? It appears that unique_name has a member_a. You already excluded the array case, which has [0]. Tuples have get<0>(tpl). There might very well be a member_a behind the get<0>, but the name member_a could be private. member_a could also be less const-qualified than get<0>.

But yes, for the most simple case, a simple struct without bitfields, there will indeed be a corresponding member_a.

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