in abstraction:
int i = 1;
auto go = [] () {
return i;
};
Is it possible to make something like that in modern C++ syntax?
Formally speaking, the ability to access the surrounding context is the key difference between a function (which cannot) and a closure (which can). Depending on the languages this capture of the environment may occur via copy or reference.
In C++11 (and beyond), lambdas are closures and as usual with C++ we have a fine-grained way of specifying how the capture is done:
[=]() { return i; }
or explicitly [i]() { return i; }
[&]() { return i; }
or explicitly [&i]() { return i; }
and C++14 even introduces generalized lambda captures, so you can capture:
[i = std::move(i)]() { return i; }
[i = 1]() { return i; }
The square brackets delimit the capture list.
Sure, depends on whether you want to capture it by value:
auto go = [i] () {
return i;
};
Or by reference:
auto go = [&i] () {
return i;
};
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