revision #1: 第二章前半部分内容完整支持 C++17

This commit is contained in:
Changkun Ou
2018-04-02 00:27:13 +02:00
parent 68db38ccb7
commit 11efa38dba
2 changed files with 462 additions and 257 deletions

View File

@@ -78,41 +78,7 @@ return _tuple_index<0>(i, tpl);
}
```
### 结构化绑定(Structured bindings)
结构化绑定提供了类似其他语言中提供的多返回值的功能。到目前为止,我们可以通过 `std::tuple` 来构造一个元组,囊括多个返回值。但缺陷是显而易见的,我们没有一种简单的方法直接从元组中拿到并定义元组中的元素,尽管我们可以使用 `std::tie` 对元组进行拆包,但我们依然必须非常清楚这个元组包含多少个对象,各个对象是什么类型。
C++17 给出的结构化绑定可以让我们写出这样的代码:
```cpp
std::tuple<int,double,std::string> f() {
return std::make_tuple(1,2.3,"456");
}
auto [x,y,z] = f(); // x,y,z 分别被推导为int,double,std::string
```
### 变量声明的强化
变量的声明在虽然能够位于任何位置,甚至于 `for` 语句内能够声明一个临时变量 `int`,但始终没有办法在 `if``switch` 语句中声明一个临时的变量。例如:
```cpp
auto p = map_container.try_emplace(key, value);
if(!p.second) {
//...
} else {
//...
}
```
C++17 消除了这一限制,使得我们可以:
```cpp
if (auto p = m.try_emplace(key, value); !p.second) {
//...
} else {
//...
}
```
## 三、未入选特性