Search code examples
c++lambdacapture

How can I capture a function result in a lambda?


I was wondering if I can capture a function result:

int main()
{
    struct A { int a; int func() { return a; } };

    A a;

    
    auto lambda = []() {};
    // I WANT THE LAMBDA TO HAVE A COPY OF a.func();
    // In other words I want capture the return value of a.func()


   
}

Is there a way to do this? I know that in newer standards of C++ you can create new variables in the capture list, so something like this?

auto lambda = [int copy = a.func()] () {   cout << copy; }

Solution

  • The syntax is slightly different. The type of the entity in the capture group is deduced from the initializer, and you can't explicitly specify the type:

    auto lambda = [copy = a.func()] () { std::cout << copy; };
               // ^ no int
    

    You can create multiple entities of different types in the capture group as well, if you just separate them by ,:

    auto lambda = [x = a.func(), y = a.func2()] () { std::cout << x << y; };
    

    Here's a demo.