In C++11 one can write lambdas with captures (and that's awesome!)
auto myfunc = [&] (int i) {return i + j;}; // j being somewhere in the lambda's context
That is awesome! However, it would be very nice if one could return such a lambda from a function, or even from another lambda. Is this possible at all?
In C++11, you'd have to wrap it in a function object of known type to return it from a function:
std::function<int(int)> get_lambda() {
return [&] (int i) {return i + j;};
}
In C++14, you can use auto to return the lambda type itself:
auto get_lambda() {
return [&] (int i) {return i + j;};
}
In either dialect, you could return it from a lambda:
auto get_lambda = [&] {return [&] (int i) {return i + j;};};
Note that you wouldn't want to return this particular lambda, since it captures a reference to a local variable j. The variable will be destroyed, leaving the reference invalid, when the function returns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With