From 78b1cdf6bb454a7ed067fc2e81faa719a847935d Mon Sep 17 00:00:00 2001 From: "A. Jiang" Date: Tue, 21 May 2024 05:58:17 +0800 Subject: [PATCH] book: correct description of function template deduction from `auto` (#280) --- book/en-us/02-usability.md | 16 +++++++++++----- book/zh-cn/02-usability.md | 17 +++++++++++------ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/book/en-us/02-usability.md b/book/en-us/02-usability.md index 51d3edc..eb8a21a 100644 --- a/book/en-us/02-usability.md +++ b/book/en-us/02-usability.md @@ -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: @@ -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 diff --git a/book/zh-cn/02-usability.md b/book/zh-cn/02-usability.md index 11047e7..c39f60a 100644 --- a/book/zh-cn/02-usability.md +++ b/book/zh-cn/02-usability.md @@ -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; ``` > @@ -413,7 +418,7 @@ type z == type x ### 尾返回类型推导 -你可能会思考,在介绍 `auto` 时,我们已经提过 `auto` 不能用于函数形参进行类型推导,那么 `auto` 能不能用于推导函数的返回类型呢?还是考虑一个加法函数的例子,在传统 C++ 中我们必须这么写: +你可能会思考, `auto` 能不能用于推导函数的返回类型呢?还是考虑一个加法函数的例子,在传统 C++ 中我们必须这么写: ```cpp template