Ежедневный бит (e) C++ # 162, структурированные привязки C++ 17
Структурированные привязки были введены в C++17.
Они позволяют разлагать массивы, кортежи и нестатические элементы данных на именованные идентификаторы.
Исходный объект захватывается в соответствии со стандартными правилами вывода для авто; идентификаторы фактически являются прозрачными ссылками на захваченный объект.
#include <unordered_set> #include <string> struct UserType { int a; double b; std::string c; }; // typical use case for structured binding to decompose // a pair returned by some standard library operations std::unordered_set<int> data{1, 2, 3, 4, 5}; if (auto [it, inserted] = data.insert(4); inserted) { // insertion happened // it points to the newly inserted element } else { // no insertion happened // it points to the existing element } // Normal auto deduction rules still apply std::pair a{10,20}; // mutable const std::pair b{10,20}; // immutable auto [i,j] = a; // Capture by copy i = 0; j = 0; // OK // a.first == 10, a.second == 20 auto &[k,l] = a; // Capture by reference k = 0; l = 0; // OK // a.first == 0, a.second == 0 auto &[m,n] = b; // Capture by reference, auto will deduce const // m = 0; j = 0; // Not OK, cannot mutate read-only variable UserType u{42, 3.14, "Hello World!"}; // Decomposing an aggregate auto &[x,y,z] = u; // x == 42, y == 3.14, z == "Hello World!"
Откройте пример в Compiler Explorer.