Is it possible in C++11 / 14 syntax to write an lambda function which will see parent variables?

c++, c++11, lambda

Solution

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:

- by copy: implicitly `[=]() { return i; }` or explicitly `[i]() { return i; }`

- by reference: implicitly `[&]() { return i; }` or explicitly `[&i]() { return i; }`

and C++14 even introduces generalized lambda captures, so you can capture:

- by move: existing variable `[i = std::move(i)]() { return i; }`

- or create a new variable `[i = 1]() { return i; }`

The square brackets delimit the capture list.

Problem

in abstraction: ``` int i = 1; auto go = [] () { return i; }; ``` Is it possible to make something like that in modern C++ syntax?

Original source