Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

lambda

in abstraction:

int i = 1;
auto go = [] () {
    return i;
};

Is it possible to make something like that in modern C++ syntax?

like image 689
cnd Avatar asked Feb 03 '14 10:02

cnd


2 Answers

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.

like image 136
Matthieu M. Avatar answered Nov 03 '22 02:11

Matthieu M.


Sure, depends on whether you want to capture it by value:

auto go = [i] () {
    return i;
};

Or by reference:

auto go = [&i] () {
    return i;
};
like image 6
Joseph Mansfield Avatar answered Nov 03 '22 03:11

Joseph Mansfield