概述
C++ 11 中的 Lambda 運算式用于定義并創建匿名的函式物件,以簡化編程作業,Lambda 的語法形式如下:
[捕獲串列] (引數) mutable 或 exception 宣告 -> 回傳值型別 {函式體}
//計算兩個值的和
auto func = [](int a, int b) -> int{return a+b;};
//當回傳值的型別是確定時,可以忽略回傳值
auto func = [](int a, int b){return a + b;};
//呼叫
int sum = func(1, 3);
語法分析
捕獲串列
Lambda 運算式相當于一個類,那么捕獲串列就是傳遞給這個類的類成員,比如:
class Labmda
{
public:
const int test;
Labmda(int value):test(value)
{
}
public:
int run(int a, int b)
{
return a + b + test;
}
}
int main()
{
int test = 10;
auto func = Labmda(test);
int sum = func.run(1, 3);
}
//使用Lambda 運算式的寫法
int main()
{
int test = 10;
auto func = [test](int a, int b){return a + b + test;};
int sum = func(1, 3);
}
捕獲串列有以下格式:
| 格式 | 描述 |
|---|---|
| [] | 不帶任何引數 |
| [=] | Lambda運算式之前的區域變數,包括所在類的this,變數按值方式傳遞 |
| [&] | Lambda運算式之前的區域變數,包括所在類的this,變數按參考方式傳遞 |
| [this] | Lambda運算式所在類的this |
| [a] | Lambda運算式之前的區域變數a的值,也可以傳入多個值,如[a , b] |
| [&a] | Lambda運算式之前的區域變數a的參考 |
關鍵字宣告
關鍵字宣告一般都很少用到,也不建議隨便使用,可以忽略不計,
mutable
當捕獲串列以值的方式傳遞時有效,加上此關鍵字后,可以修改Lambda類成員(帶const修飾符),比如:
int test = 10;
//編譯報錯,test成員不能修改
auto func = [test](int a, int b){test = 8; return a + b + test;};
//編譯正常
auto func = [test](int a, int b)mutable {test = 8; return a + b + test;};
這里需要注意的是:Lambda類成員test修改之后,并不會改變外部int test的值,
exception
exception 宣告用于指定函式拋出的例外,如拋出整數型別的例外,可以使用 throw(int)
示例
捕獲串列按值傳遞
int test = 10;
auto func = [=](int a, int b){return a + b + test;};
auto func2 = [test](int a, int b){return a + b + test;};
int sum = func(1, 3); //sum等于14
這里需要注意的是func運算式中test的值只更新到運算式之前:
int test = 10;
auto func = [=](int a, int b){return a + b + test;};
test = 5;
int sum = func(1, 3); //sum還是等于14
捕獲串列按參考傳遞
int test = 10;
auto func = [&](int a, int b){test = 5; return a + b + test;};
auto func2 = [&test](int a, int b){test = 5; return a + b + test;};
int sum = func(1, 3); //sum等于9,test等于5
這里func運算式中test的值就能隨時更新:
int test = 10;
auto func = [&](int a, int b){return a + b + test;};
test = 5;
int sum = func(1, 3); //sum等于9,test等于5
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/314681.html
標籤:C++
上一篇:在開關的情況下,條件被忽略了
