概念
lambda表达式: [capture list](params list) mutable exception-> return type {function body}也叫匿名函数。
对于一个函数而言,由4部分组成:
返回值类型 函数体(形参列表)
{
函数体;
}
而针对匿名函数,因为没有名字,定义时即使用,它由以下几部分组成:
[捕获列表] (形参列表)-->返回值类型
{
函数体;
}
匿名函数的声明和调用
普通函数的调用是通过函数名()的方式调用的,而匿名函数没有函数名则是使用匿名函数()的方式调用的。
[](){}; //匿名函数声明
[](){} (); //匿名函数的调用
参数列表
普通函数参数列表:
int fun(int a, int b); //声明
fun(1, 2)
匿名函数参数列表:
[](int a, int b){};
[](int a, int b){}(1, 2); //使用
返回值,可以通过->type的方式指定返回值类型。
auto ret = [](auto a, auto b){ return a+b; }(1, 1.5);
auto retInt = [](auto a, auto b) ->int{return a + b; }(1, 1.5); //输出为2