Skip to content

Commit

Permalink
book: correct description of function template deduction from auto (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
frederick-vs-ja committed May 20, 2024
1 parent 5c50dbc commit 78b1cdf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
16 changes: 11 additions & 5 deletions book/en-us/02-usability.md
Original file line number Diff line number Diff line change
Expand Up @@ -418,17 +418,23 @@ auto i = 5; // i as int
auto arr = new auto(10); // arr as int *
```

Since C++ 20, `auto` can even be used as function arguments. Consider
the following example:
Since C++ 14, `auto` can even be used as function arguments in generic lambda expressions,
and such functionality is generalized to normal functions in C++ 20.
Consider the following example:

```cpp
int add(auto x, auto y) {
auto add14 = [](auto x, auto y) -> int {
return x+y;
}

int add20(auto x, auto y) {
return x+y;
}

auto i = 5; // type int
auto j = 6; // type int
std::cout << add(i, j) << std::endl;
std::cout << add14(i, j) << std::endl;
std::cout << add20(i, j) << std::endl;
```
> **Note**: `auto` cannot be used to derive array types yet:
Expand Down Expand Up @@ -481,7 +487,7 @@ type z == type x

### tail type inference

You may think that when we introduce `auto`, we have already mentioned that `auto` cannot be used for function arguments for type derivation. Can `auto` be used to derive the return type of a function? Still consider an example of an add function, which we have to write in traditional C++:
You may think that whether `auto` can be used to deduce the return type of a function. Still consider an example of an add function, which we have to write in traditional C++:

```cpp
template<typename R, typename T, typename U>
Expand Down
17 changes: 11 additions & 6 deletions book/zh-cn/02-usability.md
Original file line number Diff line number Diff line change
Expand Up @@ -354,17 +354,22 @@ auto i = 5; // i 被推导为 int
auto arr = new auto(10); // arr 被推导为 int *
```

从 C++ 20 起,`auto` 甚至能用于函数传参,考虑下面的例子:
从 C++ 14 起,`auto` 能用于 lambda 表达式中的函数传参,而 C++ 20 起该功能推广到了一般的函数。考虑下面的例子:


```cpp
int add(auto x, auto y) {
auto add14 = [](auto x, auto y) -> int {
return x+y;
}

auto i = 5; // 被推导为 int
auto j = 6; // 被推导为 int
std::cout << add(i, j) << std::endl;
int add20(auto x, auto y) {
return x+y;
}

auto i = 5; // type int
auto j = 6; // type int
std::cout << add14(i, j) << std::endl;
std::cout << add20(i, j) << std::endl;
```
>
Expand Down Expand Up @@ -413,7 +418,7 @@ type z == type x

### 尾返回类型推导

你可能会思考,在介绍 `auto` 时,我们已经提过 `auto` 不能用于函数形参进行类型推导,那么 `auto` 能不能用于推导函数的返回类型呢?还是考虑一个加法函数的例子,在传统 C++ 中我们必须这么写:
你可能会思考, `auto` 能不能用于推导函数的返回类型呢?还是考虑一个加法函数的例子,在传统 C++ 中我们必须这么写:

```cpp
template<typename R, typename T, typename U>
Expand Down

0 comments on commit 78b1cdf

Please sign in to comment.