Skip to content

Structured Binding (C++17)

One-Liner

A single line of syntax that destructures elements of a tuple, pair, struct, or array into separate variables simultaneously, eliminating std::tie and per-field access.

None (language feature)

Core API Cheat Sheet

Binding FormSyntaxDescription
By valueauto [x, y] = ...;Copies elements to new variables
Lvalue referenceauto& [x, y] = ...;Binds to references of the original object
Read-only referenceconst auto& [x, y] = ...;Const reference, avoids copying
Forwarding referenceauto&& [x, y] = ...;Perfect forwarding semantics
Array destructuringint arr[3]; auto& [x, y, z] = arr;Binds to array elements (count must match)
Pair destructuringauto& [key, val] = pair;Binds to first/second of a pair
Tuple destructuringauto& [a, b] = tuple;Binds to tuple-like elements
Struct destructuringauto& [x, y] = struct_obj;Binds to public data members (declaration order)

Minimal Example

cpp
#include <iostream>
#include <tuple>

int main() {
    // 1. Pair destructuring
    std::pair<int, int> coord{10, 20};
    auto& [x, y] = coord; // Bind by reference
    x = 30;               // Modifies coord.first

    // 2. Struct destructuring
    struct Sensor { int id; float value; };
    Sensor s{1, 3.14f};
    auto [id, val] = s;   // Bind by value (copy)

    // 3. Array destructuring
    int data[3] = {1, 2, 3};
    auto& [a, b, c] = data;

    std::cout << x << ", " << y << "\n"; // 30, 20
}

Embedded Applicability: High

  • Pure compile-time syntactic sugar with zero runtime overhead; generated code is equivalent to manual field access.
  • Simplifies unpacking of multi-field structures like register sets or sensor data, improving readability.
  • Use const auto& to avoid copying, ideal for read-only access to hardware-mapped structs.
  • C++17 is fully supported in mainstream embedded toolchains (GCC 7+, ARM Clang 6+).

Compiler Support

GCCClangMSVC
74.019.1

See Also


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05