结构化绑定是 C ++17 引入的语法糖,用于直接从聚合类型(如 struct、数组、tuple)中按顺序解构成员;要求类型为聚合类(无用户构造函数、无私有 / 保护非静态成员、无基类),如 auto [x, y, z] = get_origin();。

结构化绑定是 C ++17 引入的语法糖,用于直接从结构体、数组、tuple 等可解构类型中按名称或顺序提取成员,省去手动写 get()、.first/.second 或临时变量的繁琐步骤。
基本用法:绑定结构体或类的公有成员
要求类型必须是聚合类型(如 struct,无用户定义构造函数、私有 / 保护非静态成员、基类等),且所有非静态成员为公有:
struct Point {double x, y, z;}; Point get_origin() { return {0.0, 0.0, 0.0}; } auto [x, y, z] = get_origin(); // ✅ 自动推导类型,分别绑定为 double std::cout << x << "," << y << "," << z << "n"; // 输出:0, 0, 0
绑定 std::tuple 和 std::pair
无需手动调用 std::get(),支持任意 tuple-like 类型(只要提供std::tuple_size 和std::get特化):
#include #include auto get_user() { return std::make_tuple(42, "Alice", 28.5); } auto [id, name, score] = get_user(); // ✅ 推导出 int, const char*, double // id 是 int,name 是 const char*,score 是 double // 对 pair 同样简洁 std::pair p{"ready", true}; auto [status, is_valid] = p; // status: string, is_valid: bool
绑定数组
支持 C 风格数组和std::array,按索引顺序解包:
立即学习“C++ 免费学习笔记(深入)”;
int arr[3] = {10, 20, 30}; auto [a, b, c] = arr; // a=10, b=20, c=30 —— 类型自动推导为 int&(左值引用)std::array coords = {1.5, -2.3}; auto [x, y] = coords; // x 和 y 是 double&,可修改原数组 x = 99.9; // coords[0] 变为 99.9
注意事项与常见陷阱
- 绑定的是引用(对左值)或值(对右值),如
auto [a,b] = f();中若f()返回临时 tuple,则a,b是独立副本;若绑定命名变量(如auto& [a,b] = t;),则获得引用 - 不能跳过某些元素,但可用下划线占位符(C++17 不支持,C++20 起允许
auto [_, name, _] = t;) - 结构体若有私有成员或自定义构造函数,需显式提供
std::tuple_size和std::get特化才能支持绑定(即“定制点”方式) - 绑定名不能重复,也不能是关键字,且必须全部声明在同一行