lambda表达式
从functor开始
C++中functor仿函数就是使用起来向函数的一种对象,通过重载()运算符来实现,例如下面定义的Plus类,每一个实例调用()运算符,返回参数加固定的一个值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <iostream> class Plus { int value; public: Plus(int v):value(v){}; int operator() (int x) const { return x + value; } }; int main(){ Plus plus5(5); std::cout << plus5(40); }
|
对于这样的仿函数类,我们只调用了(),此外还需要类中有一个成员变量value,其它的都是语法规范。通过使用lambda表达式,我们可以省略这些繁琐的代码,如下面这段代码,我们只需要一个value,传入参数以及函数体。
1 2
| auto plus5 = [value = 5](int x){return x + value;}; std::cout << plus5(40);
|
实际上lambda表达式就类似一个functor,对于上方lambda语句,实际上它等价于:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class __lambda_2_15 { public: inline int operator()(int x) const { return x + value; } private: int value; public: __lambda_2_15(const int & _value) : value{_value} {} }; __lambda_2_15 plus5 = __lambda_2_15{5};
|
一个lambda表达式会创建一个匿名的类(effective c++ 称作闭包类closure class), 等式左边就是lambda创建的运行时对象(或者称作闭包closure), 对象持有数据的拷贝或者引用(当作类成员变量)。使用lambda表达式,就类似于使用一个匿名的functor。 而在functor类中,还可以有函数模板:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Plus { int value; public: Plus(int v):value(v){}; template <class T> T operator() (T x) const { return x + value; } }; int main(){ auto plus1 = Plus(1); std::cout << plus1(2); std::cout << plus1(3.14); }
|
这个functor就类似于下面这段语句。
1 2 3
| auto plus1 = [value = 1](auto x){return x + value;}; std::cout << plus1(2); std::cout << plus1(3.14);
|
但是要注意的是,函数模板并不是函数,在传入参数时,编译器会进行类型推导,进而实例化一个函数出来。例如对于plus1(3.14)编译器就会特化一个函数:
1 2 3 4 5
| template<> inline double operator()(double x) const { return x + static_cast<double>(value); }
|
因此对于下面这段代码,运行时实际有两个静态变量,分别在对应的函数中定义。
1 2 3 4 5 6 7 8 9 10
| int main(){ auto plus1 = [value = 1](auto x){ static int a = 0; return x + value + (a++); }; std::cout << plus1(2)<<std::endl; std::cout << plus1(3.14)<<std::endl; std::cout << plus1(3)<<std::endl; std::cout << plus1(1.1)<<std::endl; }
|