c++lambda

C++ Returning a lambda's return value


Please help, as there are only so many ways to search "return a lambda return value" before you lose your mind!

int someFunction(){
    return [](int a){ return a; };
}

I want to return the value, not the lambda.


Solution

  • Lambda is (in a great simplification) just a function. You need to call it to have its body executed. Since this lambda requires one argument, you can call it for example with (13), so

    return [](int a){ return a; }(13);
    // or a version with easier syntax
    auto lambda = [](int a){ return a; };
    return lambda(13);
    

    Although at this point there is no point in using lambda and you should just

    return 13;