samedi 28 septembre 2019

Making sense of nested lambda expression

My question pertains to the following nested lambda expression, provided as an example under Lambda expressions

// generic lambda, operator() is a template with one parameter
auto vglambda = [](auto printer) {
    return [=](auto&&... ts) // generic lambda, ts is a parameter pack
    { 
        printer(std::forward<decltype(ts)>(ts)...);
        return [=] { printer(ts...); }; // nullary lambda (takes no parameters)
    };
};
auto p = vglambda([](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; });
auto q = p(1, 'a', 3.14); // outputs 1a3.14
q();                      // outputs 1a3.14

The following is the way I interpret the above expression:

In the expression

auto p = vglambda([](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; });

the closure object vglambda is initialized with the closure object printer whose type corresponds to the lambda expression

[](auto v1, auto v2, auto v3) { std::cout << v1 << v2 << v3; }

Inside printer, the nested (anonymous) lambda expression

return [=](auto&&... ts){}

captures printer by copy and its parameter pack as rvalue reference.

Inside the body of the (anonymous) lambda expression, the expression

printer(std::forward<decltype(ts)>(ts)...);

forwards the parameter pack to printer [in what essentially appears to be an invocation of printer using operator ()]

In the final expression inside the body of the (anonymous) lambda expression, the (anonymous) nullary lambda expression appears to capture the printer closure object from the enclosing scope by copy, along with the parameter pack, and invokes the printer closure object with its forwarded parameter pack.

return [=] { printer(ts...); };

Now, it is very evident that I am not getting something right here. Essentially, why are two distinct lines of invoking the printer closure object provided within the body of the (anonymous) lambda expression, one without the (anonymous) nullary lambda expression, and one within?

Can any of the experts throw more light?

Aucun commentaire:

Enregistrer un commentaire