Which three kinds of types can a C++ structured binding unpack, and what does each kind require of the type?
answer
- one hidden object, then names into it
- arrays by element count
- tuple_size, tuple_element and get
- accessible members of one class
- names must match the size
basics
~20 sStructured bindings unpack arrays by element, tuple-like types through std::tuple_size, std::tuple_element and get<i>, and other classes through their non-static data members, which must be accessible and declared in one class. The number of names must match.
solid answer
~50 s`auto [a, b] = expr;` first creates one hidden variable `e` initialized from `expr` (a copy, or a reference with `auto&`), then makes each name refer into `e`. Three protocols decide what the names refer to, tried in order. An **array** binds one name per element. A type for which `std::tuple_size<E>` is a complete type with a `value` member is **tuple-like**: element `i` comes from a member `e.get<i>()` if `E` declares a suitable member `get`, otherwise from `get<i>(e)` found by argument-dependent lookup. Any other class binds its **non-static data members** in declaration order; they must be accessible where the binding appears, all belong to `E` or to one base class, and include no anonymous union. In every case the count of names must equal the size, except that C++26 lets one name be a pack.
code
cpp · 30 lines#include <iostream>
#include <map>
#include <string>
#include <tuple>
struct Reply { int status; std::string payload; double latencyMs; };
Reply fetch() { return {200, "body", 12.5}; }
int main() {
auto [status, payload, latency] = fetch(); // data members, in declaration order
int codes[2] = {200, 404};
auto [first, second] = codes; // array: binds into a copy of codes
first = 500;
auto& [r0, r1] = codes; // auto&: binds into codes itself
r1 = 410;
std::cout << codes[0] << ' ' << codes[1] << '\n'; // 200 410
std::map<std::string, int> hits{{"/health", 1}};
for (auto& [path, count] : hits) ++count; // tuple-like: std::pair
std::cout << hits["/health"] << '\n'; // 2
std::tuple<int, std::string> t{1, "x"};
auto [n, s] = t; // tuple-like: std::tuple
std::cout << status << ' ' << payload << ' ' << latency << ' '
<< second << ' ' << n << s << '\n';
auto log = [status] { return status; }; // capturing a binding needs C++20
std::cout << log() << '\n';
}go deeper
Recall that structured bindings unpack pairs, tuples, arrays and simple structs, and that the number of names must match.
Explain the hidden object, the three protocols in order, and why auto& changes the original while auto does not.
Show how you would give a domain type a tuple-like interface, and diagnose a binding that silently copies a large object in a hot loop.
Decide which public types should support unpacking, since adding a data member breaks every binding of that type, and set the rule accordingly.
## One hidden object, then names into it A **structured binding declaration** such as `auto [status, payload, latency] = fetch();` (C++17) does not declare three ordinary variables. The standard describes it in two steps: 1. It introduces **one variable with a unique, invisible name**, called `e` in the wording, initialized from the expression. With plain `auto`, `e` is a new object (copied from an lvalue, moved from an xvalue, initialized directly from a prvalue); with `auto&` or `const auto&`, `e` is a reference to the original object. 2. Each name then **refers into `e`**: to an element, a member, or the result of a `get` call. This is why `auto [a, b] = codes;` on an array does not touch `codes` when you assign to `a`, while `auto& [a, b] = codes;` does. The exact declared types of the names are the business of the material on type deduction; what matters here is which protocol supplies the parts. ## The three protocols, tried in order | Protocol | Applies when | Each name refers to | Size | |---|---|---|---| | Array | `E` is an array type of known bound | element `i` of `e` | number of elements | | Tuple-like | `std::tuple_size<E>` is a complete type with a member `value` | the result of `e.get<i>()` or `get<i>(e)` | `std::tuple_size<E>::value` | | Data members | any other class type | non-static data member `i` in declaration order | number of non-static data members | ### Arrays Only arrays of known bound work; an array of unknown bound is ill-formed. A function parameter declared as `int a[]` is really a pointer and cannot be unpacked at all. ### Tuple-like types `std::pair`, `std::tuple` and `std::array` qualify because the library specializes `std::tuple_size` and `std::tuple_element` for them. Your own class can opt in by specializing both traits and providing `get`. The binding looks for `get` in a specific way: - if a lookup of `get` inside `E` finds a member function template whose first template parameter is a constant (non-type) parameter, it calls `e.get<i>()`; - otherwise it calls `get<i>(e)` using **argument-dependent lookup only**, so a `get` that is merely visible by ordinary unqualified lookup is not found. ### Plain classes When neither of the first two applies, the binding uses data members. The rules are strict: - every non-static data member must be **accessible** where the binding is written, so a class with one private member cannot be unpacked outside its own members and friends; - all non-static data members must be direct members of `E` or of **the same base class**, so members split between a base and a derived class are rejected; - `E` must not have an **anonymous union** member; - a bit-field member yields a name that behaves as a bit-field. The class does not have to be an aggregate: a class with constructors unpacks fine as long as the member rules hold. ## The count must match The number of names must equal the size the protocol reports. There is no way to skip a trailing element in C++23; you bind it and ignore the name. Clang reports a mismatch as "type 'Pair2' decomposes into 2 elements, but 3 names were provided". C++26 relaxes this with **structured binding packs**: `auto [first, ...rest] = t;` binds the remaining elements to a pack, inside a template. ## What changed after C++17 - **C++20** allows capturing a structured binding in a lambda and declaring bindings `static` or `thread_local`. Apple clang 21 accepts a capture in `-std=c++17` mode only with the warning "captured structured bindings are a C++20 extension". - **C++26** adds binding packs, attributes on individual names, `constexpr` and `constinit` bindings, and a structured binding declaration as the condition of an `if` or `while`, which tests the hidden object `e`. ## Where interviewers probe The usual middle-level probe is a `std::map` loop: `for (auto& [key, value] : m)` binds through `std::pair`'s tuple-like protocol, and `key` is `const` because the map's element type is `std::pair<const Key, T>`. The second probe is the copy: `auto [x, y] = big_struct;` copies the whole struct once into `e`, not member by member, and later writes through `x` change that copy, never the original.
- How do you make your own class unpackable through the tuple-like protocol instead of its data members?Specialize `std::tuple_size<MyType>` with a `value` member and `std::tuple_element<I, MyType>` with a `type` member, then provide `get<I>` either as a member function template or as a free function the binding finds by argument-dependent lookup, usually in the class's namespace. This lets a class with private members expose a chosen view, such as a name and an id, in a chosen order.
- In for (auto& [key, value] : m) over a std::map, why can you not assign to key?The map's element type is `std::pair<const Key, T>`. The binding goes through the pair's tuple-like protocol, and `std::tuple_element<0, ...>` is `const Key`, so `key` names a `const` object inside the element. That protects the map's ordering invariant; changing a key means extracting the node or erasing and re-inserting.
- Does auto [a, b] = s; copy each member separately into a and b?No. It copies `s` once into a single hidden object, and `a` and `b` are names for that object's members. Assigning to `a` changes the hidden copy, not `s`. With `auto& [a, b] = s;` the hidden object is a reference to `s`, so writes reach the original.
- structured bindings only work on std::pair and std::tuple
- a struct must be an aggregate to be unpacked
- auto [a, b] = s; declares a and b as independent copies of each member
- you can leave out trailing names to skip elements
- private members are unpacked as long as the names match
- a binding finds get through ordinary unqualified lookup
Assumes C++17 structured bindings as amended: lambda capture of a binding needs C++20, and binding packs, constexpr bindings and bindings as conditions are C++26.