Understand structured binding in C++17 by analogy

后端 未结 1 1651
心在旅途
心在旅途 2020-12-20 12:58

I\'m trying to understand structured binding introduced in C++17. The explanation on cppreference is not obvious to me, but it looks like

cv-auto ref-operato         


        
相关标签:
1条回答
  • 2020-12-20 13:44

    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.

    0 讨论(0)
提交回复
热议问题