1 Introduction
C++17语言上(语言特性,而不是标准库新特性)引入了一种结构化绑定的新特性,使用该特性可以利用auto同时声明多个不同类型的变量并即时从一个tuple-like对象得到赋值/初始化。
Structured binding不但可以使C++的代码更加简洁,而且似乎从语法上更贴近Python这种脚本语言了。另外,auto变量会在编译时推导出变量的类型,所以无需担心会有运行时效率的下降。而且,好像也并不会影响到编译效率,这一点尚未看到有实测。
2 Structured binding尝鲜
在C++17之前,如果要接收从函数返回的std::tuple
对象,我们可以使用std::tie
std::set<S> mySet;
S value{
42, "Test", 3.14};
std::set<S>::iterator iter;
bool inserted;
// unpacks the return val of insert into iter and inserted
std::tie(iter, inserted) = mySet.insert(value);
if (inserted)
std::cout << "Value was inserted\n";
但是在C++17中,利用Structured binding特性,可以这样处理使得代码更精简
std::set<S> mySet;
S value{
42, "Test", 3.14};
//use 'const auto' if necessary
auto [iter, inserted] = mySet.insert(value);
上述代码片段的完整代码为(传送门):
#include <iostream>