C++ 11 标准的,Lambda表达式,基本语法如下:
[capture list] (parameter list) -> return type { function body }
测试代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdio.h> int main() { int a = 4, b = 5; /* 注意,这是一个语句,分号结尾 */ auto function = [](int x, int y) -> int { return x + y; }; printf("%d\n", function(a,b)); return 0; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> using namespace std; class A{ public: void operator()(){ cout << "void operator()()" << endl; } }; template<typename T> void func(T t){ // t不是T类型的引用 cout << "template<typename T> void func(T t)" << endl; t(); //! } void test(int arg ){ int x = 2; func<A > (A() ); //对象//仿函数 func<void(*)() > ([]() { cout << "[]() { }" << endl; } ); //函数指针//lambda表达式 /* //void (*fun)() = []() { cout << "[]() { }"; }; //lambda表达式加上分号才是语句! auto p1 = [=](int i )->double { cout << arg+x+i << endl; return 0.123; }; //1+2+7 cout << p1(7 ) << endl; auto p2 = []{cout << "p2" << endl; }; //lambda表达式,必须永远包含捕获列表和函数体 p2(); */ } int main () { test(1); return 0; }