book: correct description of function template deduction from auto (#280)

This commit is contained in:
A. Jiang
2024-05-21 05:58:17 +08:00
committed by GitHub
parent 5c50dbc591
commit 78b1cdf6bb
2 changed files with 22 additions and 11 deletions

View File

@@ -418,17 +418,23 @@ auto i = 5; // i as int
auto arr = new auto(10); // arr as int * auto arr = new auto(10); // arr as int *
``` ```
Since C++ 20, `auto` can even be used as function arguments. Consider Since C++ 14, `auto` can even be used as function arguments in generic lambda expressions,
the following example: and such functionality is generalized to normal functions in C++ 20.
Consider the following example:
```cpp ```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; return x+y;
} }
auto i = 5; // type int auto i = 5; // type int
auto j = 6; // 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: > **Note**: `auto` cannot be used to derive array types yet:
@@ -481,7 +487,7 @@ type z == type x
### tail type inference ### 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 ```cpp
template<typename R, typename T, typename U> template<typename R, typename T, typename U>

View File

@@ -354,17 +354,22 @@ auto i = 5; // i 被推导为 int
auto arr = new auto(10); // arr 被推导为 int * auto arr = new auto(10); // arr 被推导为 int *
``` ```
从 C++ 20 起,`auto` 甚至能用于函数传参,考虑下面的例子: 从 C++ 14 起,`auto` 能用于 lambda 表达式中的函数传参,而 C++ 20 起该功能推广到了一般的函数。考虑下面的例子:
```cpp ```cpp
int add(auto x, auto y) { auto add14 = [](auto x, auto y) -> int {
return x+y; return x+y;
} }
auto i = 5; // 被推导为 int int add20(auto x, auto y) {
auto j = 6; // 被推导为 int return x+y;
std::cout << add(i, j) << std::endl; }
auto i = 5; // type int
auto j = 6; // type int
std::cout << add14(i, j) << std::endl;
std::cout << add20(i, j) << std::endl;
``` ```
> >
@@ -413,7 +418,7 @@ type z == type x
### 尾返回类型推导 ### 尾返回类型推导
你可能会思考,在介绍 `auto` 时,我们已经提过 `auto` 不能用于函数形参进行类型推导,那么 `auto` 能不能用于推导函数的返回类型呢?还是考虑一个加法函数的例子,在传统 C++ 中我们必须这么写: 你可能会思考, `auto` 能不能用于推导函数的返回类型呢?还是考虑一个加法函数的例子,在传统 C++ 中我们必须这么写:
```cpp ```cpp
template<typename R, typename T, typename U> template<typename R, typename T, typename U>