1
#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?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483

2 Answers2

10

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().

ypnos
  • 50,202
  • 14
  • 95
  • 141
  • 1
    This is a C++14 feature described here: https://isocpp.org/wiki/faq/cpp14-language#lambda-captures – ypnos Oct 08 '19 at 12:03
  • Nice – in the sense of the question, but is harder to read than just renaming the parameter, which I consider more recommendable (@RohitBakoliya)... – Aconcagua Oct 08 '19 at 12:23
  • 1
    Yes, I consider this an academic question. – ypnos Oct 08 '19 at 12:26
0

I believe there is no way to do exactly what you would like to as the compiler cannot have one variable a with two different values.

xdimy
  • 46
  • 6
  • It cannot have one variable with two different values, but it can have more than one variable with the same name, quite a number of examples exist, and actually, question author asks for another one (which, as presented, is ill-formed, though). – Aconcagua Oct 08 '19 at 12:21