Bootstrap

C++结构化绑定

结构化绑定(C++17引入)

利用该特性可以把以pair, tuple, array, struct的成员赋值给多个变量。在其它语言中这个特性通常叫做unpacking.

如下函数返回 dividend被 divisor除之后的倍数和余数,

std::pair<int, int> divide_remainder(int dividend, int divisor)

在c++17之前我们要以如下方式访问这个结果

const auto result =divide_remainder(16, 3);
cout<<16/3 is ”<< result.first <<” :” << result.second<< endl

使用结构化绑定编写代码

const auto [fraction, remainder] = (divide_remainder(16, 3));
cout<<16/3 is ”<< fraction <<” :” << remainder<< endl

通过结构化绑定不仅使代码简洁,因为取了明确含义的变量名,所以代码也更易读。

  • class也可以使用结构化绑定
struct employee {
	unsigned id;
	std::string name;
	std::string role;
	unsigned salary;
};
std::vector<employee> employees;
// Initialized from somewhere 
for (const auto &[id, name, role, salary] : employees) {//在范围循环中也能用
	std::cout << "Name: " << name << "Role: " << role
	 << "Salary: " << salary << std::endl;
} 
  • 固定大小的数组也能使用
int a[3]={1, 2, 3};
auto [a1, a2, a3] = a;
cout << a1 << a2 << a3 << endl;
std::array<int, 3> aa{1,2,3};
auto [aa1, aa2, aa3] = aa;

完整语法

cv-auto ref-qualifier(optional)[identifier-list]=expression;
  1. identifier-list的变量个数必须和expression中元素完全一致
  2. 可以加上引用修饰&, &&
  3. 可以加上const, volatile
  4. expression可以是std::pair,std::tuple,固定大小数组, class,
    其中class不能有私有非静态成员,并且所有非静态成员只能出现在同一个类中。
;