David Findlay

Lambda Functions and Closures officially in C++0x

Herb Sutter just posted about the most recent ISO C++ Standards Meeting. The most exciting news is that lambda functions and closures have been officially voted into C++0x! This is really going to make taking advantage of the Standard Algorithms much more straightforward.
Here's a little taste from Herb's post:

In C++0x, you can just write:
// Calling find_if using a lambda, in C++0x:
find_if( w.begin(), w.end(),
[]( const Widget& w ) -> bool { w.Weight() > 100; } );

Yes, you can already achieve the same thing today, with a standard binary predicate and a helper, thusly:

find_if(w.begin(), w.end(), bind2nd(greater<int>(), 100));

but it isn't nearly as easy on the eye, is it?

Lambda functions will also make it a lot easier in situations where now you'd be forced to use a custom predicate; previously you'd have to: create a functor; remember to make it inherit from std::unary_function or std::binary_function for completeness; stick it in an anonymous namespace (optional but recommended; and finally, use it in your invocation of one of the standard algorithms. That works, but if you're coding a for_each, because you're trying to be good and not write a loop on an STL container by hand, then having the interesting part of the loop in a functor makes the code much harder to follow: instead of it being right there in the loop, it has to be somewhere else, breaking up the flow of the logic in the poor reviewer's head.