标签:c++11 回调函数 int 柯里化 turn 返回值 引入 type string
比方
auto lambda = [](auto x, auto y) {return x + y;};依据C++14标准,这一lambda与下面代码作用同样。struct unnamed_lambda
{
template<typename T, typename U>
auto operator()(T x, U y) const {return x + y;}
};
auto lambda = unnamed_lambda();C++14的泛型lambda能够被看做C++11的(单态)lambda的升级版。单态lambda相当于普通函数对象。而泛型lambda则相当于带模板參数的函数对象。或者说相当于带状态的函数模板。两者相比,能够推出下面结果:
泛型lambda强化了这一能力,使得泛型闭包成为可能。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// 泛型局部函数
auto f = [](auto x, auto y) { return x + y; };
cout << f(1, 3) << endl;
cout << f(string{}, "abc") << endl;
// 泛型回调函数
auto f2 = [](auto e) { cout << e << ","; };
vector<int> v1{1, 2, 3};
vector<string> v2{"a", "b", "c"};
for_each(v1.begin(), v1.end(), f2); cout << endl;
for_each(v2.begin(), v2.end(), f2); cout << endl;
// 泛型闭包
auto f3 = [](auto a) {
return [=]() mutable { return a = a + a; };
};
auto twice1 = f3(1);
cout << twice1() << endl; cout << twice1() << endl;
auto twice2 = f3(string{"a"});
cout << twice2() << endl; cout << twice2() << endl;
}
/*
4
abc
1,2,3,
a,b,c,
2
4
aa
aaaa
*/
C++14尝鲜:Generic Lambdas(泛型lambda)
标签:c++11 回调函数 int 柯里化 turn 返回值 引入 type string
原文地址:http://www.cnblogs.com/wzjhoutai/p/6714481.html