但是函数模板并不是那篇文章所追求的,以上的这段代码被称作是 a named global function. 而在最新的通过的C++14标准中引入了 generalized lambda的概念。我们允许lambda表达式的传参类型为auto类型(看来C++是要强化类型自动推导啊,auto关键字能够使用的地方越来越多了。),如下我们能够使用更短,更优雅的代码实现以上需求。
1
auto func = [](auto input){ return input * input; };
完整代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<complex>
intmain() {
// Store a generalized lambda, that squares a number, in a variable
auto func = [](auto input) { return input * input; };
// Usage examples:
// square of an int
std::cout << func(10) << std::endl;
// square of a double
std::cout << func(2.345) << std::endl;
// square of a complex number
std::cout << func(std::complex<double>(3, -2)) << std::endl;
return0;
}
#include<iostream>
#include<vector>
#include<numeric>
#include<algorithm>
intmain() {
std::vector<int> V(10);
// Use std::iota to create a sequence of integers 0, 1, ...
std::iota(V.begin(), V.end(), 1);
// Print the unsorted data using std::for_each and a lambda
std::cout <<"Original data"<< std::endl;
std::for_each(V.begin(), V.end(), [](auto i) { std::cout << i <<" "; });
std::cout << std::endl;
// Sort the data using std::sort and a lambda
std::sort(V.begin(), V.end(), [](auto i, auto j) { return (i > j); });
// Print the sorted data using std::for_each and a lambda
std::cout <<"Sorted data"<< std::endl;
std::for_each(V.begin(), V.end(), [](auto i) { std::cout << i <<" "; });
std::cout << std::endl;
return0; }