book: reword generic lambda

Fixes #242
This commit is contained in:
Changkun Ou
2022-07-17 15:08:18 +02:00
parent e50e3c64f2
commit 2e9eed9ecc
2 changed files with 9 additions and 15 deletions

View File

@@ -126,13 +126,9 @@ initialize it in the expression.
In the previous section, we mentioned that the `auto` keyword cannot be used
in the parameter list because it would conflict with the functionality of the template.
But Lambda expressions are not ordinary functions, so Lambda expressions are not templated.
This has caused us some trouble: the parameter table cannot be generalized,
and the parameter table type must be clarified.
Fortunately, this trouble only exists in C++11, starting with C++14.
The formal parameters of the Lambda function can use the `auto` keyword
to generate generic meanings:
But lambda expressions are not regular functions, without further specification on the typed parameter list, lambda expressions cannot utilize templates. Fortunately, this trouble
only exists in C++11, starting with C++14. The formal parameters of the lambda function
can use the `auto` keyword to utilize template generics:
```cpp
void lambda_generic() {
@@ -221,7 +217,7 @@ int foo(int a, int b, int c) {
;
}
int main() {
// bind parameter 1, 2 on function foo,
// bind parameter 1, 2 on function foo,
// and use std::placeholders::_1 as placeholder for the first parameter.
auto bindFoo = std::bind(foo, std::placeholders::_1, 1,2);
// when call bindFoo, we only need one param left
@@ -483,8 +479,8 @@ int main() {
// "str: Hello world."
std::cout << "str: " << str << std::endl;
// use push_back(const T&&),
// no copy the string will be moved to vector,
// use push_back(const T&&),
// no copy the string will be moved to vector,
// and therefore std::move can reduce copy cost
v.push_back(std::move(str));
// str is empty now

View File

@@ -107,11 +107,9 @@ void lambda_expression_capture() {
### 泛型 Lambda
上一节中我们提到了 `auto` 关键字不能够用在参数表里,这是因为这样的写法会与模板的功能产生冲突。
但是 Lambda 表达式并不是普通函数,所以 Lambda 表达式并不能够模板化。
这就为我们造成了一定程度上的麻烦:参数表不能够泛化,必须明确参数表类型。
幸运的是,这种麻烦只存在于 C++11 中,从 C++14 开始,
Lambda 函数的形式参数可以使用 `auto` 关键字来产生意义上的泛型:
但是 Lambda 表达式并不是普通函数,所以在没有明确指明参数表类型的情况下,Lambda 表达式并不能够模板化。
幸运的是,这种麻烦只存在于 C++11 中,从 C++14 开始Lambda 函数的形式参数可以使用 `auto`
关键字来产生意义上的泛型:
```cpp
auto add = [](auto x, auto y) {