Search code examples
c++c++11lambdafunctional-programminginline-functions

how to pass local variable and argument of same name (using this keyword )inside lambda functions in c++?


#include <iostream>
#include <functional>
int main(){
    int a = 10; 
    std::function<int(int)> functionPointer = [a](int a)-> int{ return a + a + 100 ; };
    int returnValue = functionPointer(50);
    std::cout<<returnValue<<endl;
}

I was expecting 10+50+100 = 160 but the output is 10+10+100 = 120. Are there any changes I can make to get 160, whilst keeping the variable names as they are?


Solution

  • Actually there is a way to solve this problem without changing the variable or parameter name, by aliasing the capture:

    std::function<int(int)> functionPointer = [b=a](int a)-> int{ return a + b + 100 ; };
    

    As explained here, since C++14 lambda capture is generalized, which includes renaming variables of the lambda object. While a capture [a] would copy local variable a from outer scope into a lambda object variable a, we can also name that lambda object variable with the syntax [b=a], so the lambda's copy is known as b. We can also define lambda object variables with expressions, e.g. [a=5*a] or [b=5*a], which is sometimes a neat way of e.g. passing members of a struct or results of accessor methods to a lambda.

    It allows to do things previously not possible, namely passing a unique_ptr to the lambda object (i.e. transferring ownership!) with std::move().