C++11 lambdas
Stephen Colebourne
scolebourne at joda.org
Sun Mar 14 06:21:22 PDT 2010
Apparently the C++0x specification is moving into a final stage (and
to be known as C++11)
http://herbsutter.wordpress.com/2010/03/13/trip-report-march-2010-iso-c-standards-meeting/
As C++ is similar to Java, I though it was worth having a look at what
the lambda specification is that they are planning to add
(http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions
- http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3035.pdf
section 5.1.2)
The basic lambda function is:
[](int x, int y) -> int { int z = x + y; return z + x; }
where the (int x, int y) are the arguments (optional if no arguments),
-> int is the return type (optional, can be inferred), and the {} is
the block. I note the use of local-return and round bracket
parameters.
The square brackets are used to access local variables:
int total = 0;
list.each(
[&total](int x) { total += x; }
);
Where &total "enables" the local variable to be seen and used (local
variables are not accessible by default). This technique creates a
closure. If the square brackets contain [&] then all local variables
are closed over and made available. By comparison, if the variable
name is used without the & prefix, then the variable is copied (not
closed over). [=] copies all variables in scope.
[&] - closes over all local variables including "this"
[&total] - closes over just the total variable
[=] - copies all local variables on construction including "this"
[total] - copies the total local variable on construction
[&total, value] - closes over total and copies value
[this] - copies reference to "this"
The "this" keyword does NOT appear to refer to the lambda.
There appear to be no function types.
Of course, if I've got something wrong, please correct!
So, wrt to Project Lambda
same:
- local "return"
- round bracket arguments
- curly brace blocks
- introducing symbol (# or [])
different:
- no local "this"
- optional round bracket arguments (when no args)
- optional return type
- import of local variables by reference or copy (controlled by programmer)
- no function types
I make no comment here on the up or down side of each of these differences.
Stephen
More information about the lambda-dev
mailing list