Skip to content

Commit 49a2c1b

Browse files
committed
Merge branch 'main' of github.com:parallel101/cppguidebook
2 parents ad6da82 + 75487b3 commit 49a2c1b

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

docs/auto.md

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ auto const &getConstRef() { // std::string const &
378378

379379
### 真正的万能 `decltype(auto)`
380380

381-
返回类型声明为 `decltype(auto)` 的效果等价于把返回类型替换为 `decltype((返回表达式))`
381+
返回类型声明为 `decltype(auto)` 的效果等价于把返回类型替换为 `decltype(返回操作数)`
382382

383383
```cpp
384384
int i;
@@ -387,22 +387,40 @@ decltype(auto) func() {
387387
return i;
388388
}
389389
// 等价于:
390-
decltype((i)) func() {
390+
decltype(i) func() {
391391
return i;
392392
}
393393
// 等价于:
394-
int &func() {
394+
int func() {
395395
return i;
396396
}
397397
```
398398
399-
> {{ icon.warn }} 注意 `decltype(i)` 是 `int` 而 `decltype((i))` 是 `int &`。这是因为 `decltype` 实际上有两个版本!当 `decltype` 中的内容只是单独的一个标识符(变量名)时,会得到变量定义时的类型;而当 `decltype` 中的内容不是单纯的变量名,而是一个复杂的表达式时,就会进入 `decltype` 的第二个版本:表达式版,会求表达式的类型,例如当变量为 `int` 时,表达式 `(i)` 的类型是左值引用,`int &`,而变量本身 `i` 的类型则是 `int`。此处加上 `()` 就是为了让 `decltype` 被迫进入“表达式”的那个版本,`decltype(auto)` 遵循的也是“表达式”这个版本的结果
399+
对于变量名,在 `return` 语句中加括号可以产生不同结果
400400
401401
```cpp
402402
int i;
403403
404404
decltype(auto) func() {
405-
return i;
405+
return (i);
406+
}
407+
// 等价于:
408+
decltype((i)) func() {
409+
return (i);
410+
}
411+
// 等价于:
412+
int& func() {
413+
return (i);
414+
}
415+
```
416+
417+
> {{ icon.warn }} 注意 `decltype(i)``int``decltype((i))``int &`。这是因为 `decltype` 实际上有两个版本!当 `decltype` 中的内容只是单独的一个标识符(变量名)时,会得到变量定义时的类型;而当 `decltype` 中的内容不是单纯的变量名,而是一个复杂的表达式时,就会进入 `decltype` 的第二个版本:表达式版,会求表达式的类型,例如当变量为 `int` 时,表达式 `(i)` 的类型是左值引用,`int &`,而变量本身 `i` 的类型则是 `int`。此处加上 `()` 使得 `decltype` 进入“表达式”的那个版本,`decltype(auto)` 就会遵循“表达式”这个版本的结果。
418+
419+
```cpp
420+
int i;
421+
422+
decltype(auto) func() {
423+
return i + 1;
406424
}
407425
// 等价于:
408426
decltype((i + 1)) func() {

0 commit comments

Comments
 (0)