通用Lambda在C ++ 14中如何工作?
在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) {
//定义广义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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志