Monday, September 24, 2007

Pirate name


My pirate name is:

Iron Harry Vane

A pirate's life isn't easy; it takes a tough person. That's okay with you, though, since you a tough person. You tend to blend into the background occaisionally, but that's okay, because it's much easier to sneak up on people and disembowel them that way. Arr!
piratequiz.com.

Past problems

Here is a small list of problems. The list might be incomplete, and I lost their solutions ;). Thanks to all that contributed with an idea for any task or solution.

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.