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

in abstraction:

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

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

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.


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

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

Or by reference:

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

Just put it in the capture section:

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

Need Your Help

How to use knitr from command line with Rscript and command line argument?

r knitr

I have an R code my_code.R which takes in an argument a file test.txt. I can use:

PHP OOP File upload failure $_FILES not assigning to object/method variables

php arrays oop

I've been going over an old tutorial for OOP PHP and I've hit a wall