C++

Rambda Expression

F.xavier 2014. 2. 26. 02:07
  1. Grammer

Function을 함수를 작성하지 않고 Inline 시키는 방법이며 코드가 간결해지고 가독성이 높아진다.

    process(vNum, [&cnt](int num){cnt+=isEven(num);});

[capture] (parameters) mutable exceptions -> returntype {function body}

Capture : 함수 외부에 있는 변수를 함수에서 참조하고자 할때 사용하는 변수

Parameter 목록 :

  • Default value 지정이 불가
  • Variable parameter 불가
  • Parameter name 지정

Mutable : 외부 변수는 함수 내부에서 참조할 뿐 변경이 불가능하다. 그러나mutable이 선언이 되면 변경이 가능하다.

Exception : 함수에서 throw할 수 있는 exception을 지정한다.

Return type: 생략되면 컴파일러가 자동으로 지정을 해준다.

//    1. Simple Rambda expression

    []{cout<<"Hello world" << endl;}(); // () 함수 직접 수행

 

// 2. add variable

    [](const string& str){cout<<"welcome "+ str << endl;}("to the world");

 

// 3. add return type, which can be omitted

//    string result = [](const string& str) -> string {return "hello from " + str;}("second Rambda");

    string result = [](const string& str) {return "hello from " + str;}("second Rambda");

 

    cout << "Result " << result << endl;

 

// 4. set Rambda expression to a function pointer,

    auto fn = [](const string& str){return "welcome "+ str;};

    cout << fn("to the world") << endl;

    cout << fn("to Korea") << endl;

 

  1. Capture

    [=] : all variables copy capture

    [&]:all variables reference capture : 원본 수정 가능

    [&x] : x만 레퍼런스로 캪처

    [x] : value x copy

    [=,&x] : all variables copy capture except x, capture x by reference

    [&,x]: all variables capture by reference except x, capture x by value

     

  2. As a Return type

     

  3. As a parameter