Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a lambda with captures from a function

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?

like image 729
Matteo Monti Avatar asked Nov 21 '25 00:11

Matteo Monti


1 Answers

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.

like image 59
Mike Seymour Avatar answered Nov 23 '25 14:11

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!