Apr 19, 2022

[C++] structure binding minute

Reference:
https://en.cppreference.com/w/cpp/language/structured_binding

Quick reference of structured binding rules.

Rules

  • struct MyStruct {
         int i = 0;
         std::string s;
         const int i2 = 42;
    };
    
    MyStruct ms;
    // i.e honor the structure data members' type;
    // i2 is const thus w is const int
    // e is of type of ms
    auto e = ms; 
    aliasname u = e.i; 
    aliasname v = e.s;
    aliasname w = e.i2; // w is const int
  • Apart from decltype of a const structure's data member which the result is non-const.
    Qualifier works on bound alias variable.
    // const ref to anonymous entity; however;
    //the decltype of the type's data member honors the qualifiers.
    const auto& [u,v,w] = ms;
    decltype(u);// const int
    decltype(v);// const std::string
    decltype(w);// const int
  • alignas(16) auto [u,v] = ms; // align the object, not v
  • structured bindings do not decay.
    struct S {
         const char x[6];
         const char y[3];
    };
    
    S s1{};
    auto [a, b] = s1; // a, b is of type "const char [6]", "const char [3]"
  • Structured Bindings is used in: 
    • For structures and classes where all non-static data members are public, you can bind each non-static data member to exactly one name. 
    • For raw arrays, you can bind a name to each element of the array. 
    • For any type, you can use a tuple-like API to bind names to whatever the API defines as "elements."
      The API roughly requires the following components for a type type:
      • std::tuple_size<type>::value has to return the number of elements.
      • std::tuple_element<idx,type>::type has to return the type of the idxth element.
      • A global or member get<idx>() has to yield the value of the idxth element. 
      • The standard library types std::pair<>, std::tuple<>, and std::array<> are examples of types that provide this API.
      • If structures or classes provide the tuple-like API, the API is used.
  • skip binding variable trick:
    // works only once within the same scope also applies to global namespace:
    auto [_,val1] = getStruct(); // OK
    auto [_,val2] = getStruct(); // ERROR: name _ already used

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.