C++0x specification is finally approved by ISO and the latest compilers now support most of the specification without too many bugs. One of many new features introduced is support for lambda expressions. Lambda expressions are anonymous functions that maintain state and can access variables from the enclosing scope. Well known and often used in scripting languages, they were not available in C++ until now. Their definition consists of input parameters, optional return type and optional list of external variables (closure) that will be available inside the functions. External variables can be accessed by value or by reference and there is an option for default fallback.

Simple anonymous function:

 [](int x) -> int { return x+1; }

Square brackets are used for closure definition, round brackets hold the parameter list as usual and the return type after the arrow. Return type can be omitted for functions that consist of a single return statement.

Empty closure definition means that no external variables are available inside anonymous function and trying to use one will result in error.  Other options are:

[x] // x will be accessed by value
[&x] // x will be accessed by reference
[x, &y] // x will be accessed by value and y by reference
[&] // all external variables will be accessed by reference
[=] // all external variables will be accessed by value
[=, &x] // x is accessed by reference, all other variables by value
[&, x] // x is accessed by value, all other variables by reference

Example of an lambda expression in for_each statement:

int sum(const std::vector<int>& numbers)
{
	int totalSum = 0;
	std::for_each(numbers.begin(), numbers.end(), [&totalSum](int value) { totalSum+=value; } );
	return totalSum;
}

Calling a lambda function (same syntax can be used for passing lambda functions as parameters to other functions):

auto lambda_inc = [](int x) -> int { return x+1; };
int (func_ptr*)(int) = lambda_inc;
int six = func_ptr(5);

0 comments