Native Lambda Expressions in C++? Yes Please!!

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:

 

[code lang="cpp"] replace_if(str.begin(), str.end(), is_bad_char(), '_'); [/code]

 Looks easy enough, and it’s nice and concise.  All we have to do now is define is_bad_char(), something like:

[code lang="cpp"]
struct is_bad_char: public std::unary_function
{
  bool operator() (const char& c) const
  {
    return !(c == '$' || c == '|');
  }
};
[/code]

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:

[code lang="cpp"]
replace_if(str.begin(), str.end(),
       <>(char c) -> bool { return !(c == '$' || c == '|'); },
       '_');
[/code]

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++.

1 reply

Comments are closed.