This post originated from an RSS feed registered with Java Buzz
by Weiqi Gao.
Original Post: Closures Comes To C++0x
Feed Title: Weiqi Gao's Weblog
Feed URL: http://www.weiqigao.com/blog/rss.xml
Feed Description: Sharing My Experience...
Hurb Sutter: For me, easily the biggest news of the meeting was that we voted lambda functions and closures into C++0x. I think this will make STL algorithms an order of magnitude more usable, and it will be a great boon to concurrent code where it's important to be able to conveniently pass around a piece of code like an object, to be invoked wherever the program sees fit (e.g., on a worker thread).
Here are some of the finer points of the syntax and semantics:
An lambda expression has the general form [...](...)...{...}
The [...] portion serves as a lambda introducer, it also indicates which local variables, or this, are captured from the environment
The optional (...)... portion declares the parameters, thrown exceptions and return types of the lambda expression
The {...} portion contains the code of the lambda expression
Lambda expressions evaluates to closure objects, which are function objects whose class are implicitly defined and named. There's no duck typing here. The duck typing happens in the template system
The simplest lambda expression in C++ is thus
[]{ }
which captures no local variables, takes no parameters, and performs no actions when invoked.
The most useful lambda expression will be introduced by [&], which captures every free variable in the lambda expression by reference. The [=] introducer introduces a lambda expression that captures everything by value. The [] captures nothing.
The lambda introducer may also contain an explicit list of variable names or this, in which case they are captured by the lambda expression whether explicitly referenced by the lambda expression body or not. I haven't figured out how this could be used except that it may make local variables live longer.
In C++, the closure feature is more of a syntactic sugar for function objects.
One irony here is that while in the past, we have strived to turn for loops into for_each statements, closures will make those for_each statements look (mostly) just like the for loops.