Skip to content

Structured Bindings (C++17)

In a Nutshell

Decompose tuple, pair, struct, or array elements into independent variables in a single line — no more std::get or field-by-field access.

None (language feature)

Core API Quick Reference

Binding FormSyntaxDescription
By valueauto [a, b] = expr;Copy elements into new variables
Lvalue referenceauto& [a, b] = expr;Bind to references of the original object
Const referenceconst auto& [a, b] = expr;Read-only reference, avoids copies
Forwarding referenceauto&& [a, b] = expr;Perfect forwarding semantics
Array decompositionauto [a, b, c] = arr;Bind to array elements (count must match)
Pair decompositionauto [key, val] = *map_iter;Bind to pair's first/second
Tuple decompositionauto [x, y, z] = tup;Bind to tuple-like get<I>
Struct decompositionauto [x, y] = point;Bind to public data members (declaration order)

Minimal Example

cpp
// Standard: C++17
#include <iostream>
#include <map>
#include <tuple>

struct Point { double x, y; };

int main() {
    // Struct decomposition
    Point p{1.0, 2.0};
    auto [px, py] = p;
    std::cout << px << ", " << py << "\n"; // 1, 2

    // Pair decomposition (map iteration)
    std::map<int, const char*> m{{1, "one"}, {2, "two"}};
    for (const auto& [key, val] : m) {
        std::cout << key << ": " << val << "\n";
    }

    // Tuple decomposition
    auto [a, b, c] = std::make_tuple(10, 20, 30);
    std::cout << a + b + c << "\n"; // 60
}

Embedded Applicability: High

  • Pure compile-time syntactic sugar with zero runtime overhead — generates identical code to manual field access
  • Simplifies unpacking of multi-field structures like register groups and sensor data, improving readability
  • Use with const auto& to avoid copies, ideal for read-only access to hardware-mapped structs
  • C++17 is well-supported by mainstream embedded toolchains (GCC 7+, ARM Clang 6+)

Compiler Support

GCCClangMSVC
74.019.1

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress