Skip to content

Instantly share code, notes, and snippets.

@MarcWang
Last active November 18, 2015 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarcWang/336ef438524ccfba69da to your computer and use it in GitHub Desktop.
Save MarcWang/336ef438524ccfba69da to your computer and use it in GitHub Desktop.

Lambda functions:

Syntax

1. [ capture-list ] ( params ) mutable(optional) exception attribute -> ret { body }	
2. [ capture-list ] ( params ) -> ret { body }
3. [ capture-list ] ( params ) { body }
4. [ capture-list ] { body }

capture-list

  • []:不參考匿名函式外部的任何變數。
  • [=]:參考匿名函式外部的所有變數,且都以傳值(by value)的方式。
  • [&]:參考匿名函式外部的所有變數,且都以傳參考(by reference)的方式。
  • [x, &y]:僅參考匿名函式外部的x與y變數,x變數使用傳值、y變數使用傳參考。
  • [=, &y]:參考匿名函式外部的所有變數,y變數使用傳參考,剩下所有變數皆使用傳值的方式。
  • [&, x]:參考匿名函式外部的所有變數,x變數使用傳值,剩下所有變數皆使用傳參考的方式。

mutable

  • mutable = 允許在Lambda內部修改外部變數

exception

  • throw = 回傳例外狀況

-> ret

  • -> int = 回傳值的型別

Sample Code

// 全域變數 ( Global variable )
int gX = 1, gY = 2, gZ = 3;

// []:不參考匿名函式外部的任何變數
// gX , gY and gZ 不在匿名函式的可視範圍 ( scope )
int n = [] (int x, int y) mutable throw() -> int{
    return x + y;
}( 4, 5 );
// Output: gX = 1, gY = 2, gZ = 3, n = 9


// [=]:參考匿名函式外部的所有變數,且都以傳值(by value)的方式
int n = [=] (int x, int y) mutable throw() -> int{
    gX = x;
    gY = y;
    return gX + gY + gZ;
}( 4, 5 );
// Output: gX = 1, gY = 2, gZ = 3, n = 12


//[&]:參考匿名函式外部的所有變數,且都以傳參考(by reference)的方式
int n = [&] (int x, int y) mutable throw() -> int{
    gX = x;
    gY = y;
    return gX + gY + gZ;
}( 5, 6 );
// Output: gX = 5, gY = 6, gZ = 3, n = 14


//[gX, &gY]:僅參考匿名函式外部的gX與gY變數,gX變數使用傳值、gY變數使用傳參考
// gZ 不在匿名函式的可視範圍 ( scope )
int n = [gX, &gY] (int x, int y) mutable throw() -> int{
    gX = x;
    gY = y;
    return gX + gY;
}( 6, 7 );
// Output: gX = 1, gY = 7, gZ = 3, n = 13


//[=, &gY]:參考匿名函式外部的所有變數,gY變數使用傳參考,剩下所有變數皆使用傳值的方式
int n = [=, &gY] (int x, int y) mutable throw() -> int{
    gX = x;
    gY = y;
    return gX + gY + gZ;
}( 8, 9 );
// Output: gX = 1, gY = 9, gZ = 3, n = 20


//[&, gX]:參考匿名函式外部的所有變數,gX變數使用傳值,剩下所有變數皆使用傳參考的方式
int n = [&, gX] (int x, int y) mutable throw() -> int{
    gX = x;
    gY = y;
    return gX + gY + gZ;
}( 9, 10 );
// Output: gX = 1, gY = 10, gZ = 3, n = 22

Ref : gtwang

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment