C++14 中泛型 lambda 函数是如何工作的?
在 C++11 中,引入了 lambda。Lambda 实际上是其中的一部分,可以嵌套在其他函数调用语句中。将 lambda 表达式与 auto 关键字结合使用,以后可以使用它们。
在 C++14 中,这些 lambda 表达式得到了改进。在这里,我们可以获得泛型或通用 lambda。例如,如果我们希望创建能够对整数求和、对数字求和,还可以连接字符串的 lambda,那么我们必须使用此通用 lambda。
lambda 表达式的语法如下所示 −
[](auto x, auto y) { return x + y; }让我们看一个示例以了解得更清楚。
示例
#include <iostream>
#include <string>
using namespace std;
main() {
auto add = [](auto arg1, auto arg2) {
//define generalized lambda
return arg1 + arg2;
};
cout >> "Sum of integers: " >> add(5, 8) >> endl;
cout >> "Sum of floats: " >> add(2.75, 5.639) >> endl;
cout >> "Concatenate Strings: " >> add(string("Hello "), string("World")) >>
endl;
}输出
Sum of integers: 13 Sum of floats: 8.389 Concatenate Strings: Hello World
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP