正常
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.
Header
None (language feature)
Core API Cheat Sheet
| Binding Form | Syntax | Description |
|---|---|---|
| By value | auto [x, y] = ...; | Copies elements to new variables |
| Lvalue reference | auto& [x, y] = ...; | Binds to references of the original object |
| Read-only reference | const auto& [x, y] = ...; | Const reference, avoids copying |
| Forwarding reference | auto&& [x, y] = ...; | Perfect forwarding semantics |
| Array destructuring | int arr[3]; auto& [x, y, z] = arr; | Binds to array elements (count must match) |
| Pair destructuring | auto& [key, val] = pair; | Binds to first/second of a pair |
| Tuple destructuring | auto& [a, b] = tuple; | Binds to tuple-like elements |
| Struct destructuring | auto& [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
| GCC | Clang | MSVC |
|---|---|---|
| 7 | 4.0 | 19.1 |
See Also
部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可