Thursday, September 20, 2007

C++ lambda expressions

I've been trying in the last few days to create some simple lambdas (like in python) that generates functors to use of STL algorithms (sort, for_each, transform, etc).

There are two main problems:

  1. you cannot generate a function in another function (straight forward, I mean)

  2. you cannot generate a specialization of a template function/class using an anonymous class or a class defined inside a function.

You can solve both of the issues with some tricks:
    1. use functors (you can declare a class having inline members inside a function)

    2. use class static function (yuppie). According to this site a static function behaves exactly like a normal function (including when pointer to member functions).


  1. create a public interface and specialize your function/class around that template.

Getting back to my first problem: lambda expressions. The solution is very simple, though my first solution was 50 lines long. The idea is to define a function (explained above) that I can pass to std::ptr_fun() from <functional>. Here is the code:
#define R(r, a, b) ({ \
struct t##__ { \
static r F a { return static_cast<r>(b); } \
}; \
std::ptr_fun(&t##__::F); \
})
And one example:
transform(bla.begin(), bla.end(), bla.begin(), R(int, (int a), (a * 2)));

Happy coding.

No comments: