This entry was posted on Monday, January 5th, 2009 at 7:04 pm and is filed under Tech Stuff. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Today I came across a situation which brought it home to me again how (in my opinion) C++ could desperately do with native lambda function support. The standard library has introduced a load of great algorithms, but providing predicates and the like to them is a real pain - and I think that because of this people tend to stick to hand rolling good old-fashioned loops.
Â
Consider replacing a few different characters in a std::string with a single given character, e.g., replace the characters ‘$’ and ‘|’ with ‘_’. A good way of doing this in C++ would be to use the boost regular expression library, but we could also use the std::replace_if() algorithm. All we have to do to use this algorithm is to privide a predicate that indicates if a given character should be replaced or not (say called is_bad_char()), then we do something like:
Â
replace_if(str.begin(), str.end(), is_bad_char(), ‘_’);
 Looks easy enough, and it’s nice and concise. All we have to do now is define is_bad_char(), something like:
struct is_bad_char: public std::unary_function { bool operator() (const char& c) const { return !(c == ‘$’ || c == ‘|’); } };
I mean! what a pallava!  that’s quite a mouthful, would you really be bothered? You would have a loop coded in just the time it took to start to remember that syntax, never mind the typing. it also looks terribly inelegant.
Â
Now when native lambda support arrvies we will be able to do something like this instead:
replace_if(str.begin(), str.end(), <>(char c) -> bool { return !(c == ‘$’ || c == ‘|’); }, ‘_’);
That’s much better… but not available yet, we will just have to wait for c++0x to arrive. In the mean time I will just have to use lambdas in the many other languages that support them and pine when using C++.

January 6th, 2009 at 4:11 pm
Actually there are a whole slew of features in the c++0x draft that I am looking forward to using (as explained in http://en.wikipedia.org/wiki/C%2B%2B0x). Lots of simple usability features but Lambda’s and standardisation of concurrancy features are what I think will be important/useful.