I wanted to write a lambda that returns itself, so I could call it multiple times on the spot. But it looks like inside of a lambda this
refers not to the lambda but to the surrounding object's this
, if the lambda is defines inside a member function.
Here's an example:
#include <iostream>
int main(int argc, char* argv[]) {
int a = 5;
[&](int b) {
std::cout << (a + b) << std::endl;
return *this;
}(4)(6);
}
Is there a way to do something comparable?
You can call a lambda if you assign it to a predifned type (not auto), and it gets captured:
You cant return the lambda itself, but you can return a different one:
However, this allows only to call it one more time. Not sure if there is some trick to get more out of it...
Ben Voigt proposes to use Y combinators (which are a great proposal to the standard library, BTW), but your problem is simpler. You can introduce a small template functor that will be called instead of the lambda:
Your lambda will then not even need to explicitly return anything:
With old functor:
Demo