C++11 – Part 6: Lambda Expressions

Lambda expressions provide a way to specify unnamed functions on the fly. While such a thing may seem a bit weird to those only familiar with the C family of languages, this is a fairly common feature of most programming languages.

The basic syntax of a lambda expression is:

[capture](arguments)->return-type{body}

Lets start with the common example, sorting by absolute value. Taking a std::vector<int> v, we can sort by absolute value using something like:

std::sort(v.begin(), v.end(), [](int x, int y) { return abs(x) < abs(y); } );

Walking through the parts of the lambda expression, firstly we have the capture field, []. This is a list of variables in the scope of the lambda function that are able to be accessed in the expression. In this case there is noting captured, so the capture field is empty. If we want to use variables in the scope of the lambda function, they are specified in a comma separated list within the []. For example, to calculate the sum of all items in a std::vector<int>, we could use:

int total = 0;
std::for_each(v.begin(), v.end(), [&total](int x) { total += x; } );

Note that by default variables are captured by value. The & in front of total tells the lambda function to capture it by reference and thus allow it to be changed. To capture all variables by value, use [=] and use [&] to capture all by reference. The later values in the capture field override the earlier ones, so [=, &x] captures all variables by value except for x which is captured by reference.

The arguments passed to the lambda function are just like the arguments of a normal function. Of course, the lambda function can be passed no arguments by using (). An optional return type can be provided using the suffix return syntax introduced earlier in this series. If not specified, the return type is deduced from the return statement (much like using auto), or is void if no value is returned.

That leaves the function body. Technically, any block of code can be put in the function body, but you are probably doing it wrong if the function is going to be more than a couple of lines long...

Comments are closed.