Tuesday, June 30, 2009

Coolest postcard ever

I received the maybe coolest postcard ever today. It's from a pal I know from IRC (#c++.de on quakenet) who has been living in Madagascar for a few years now. He's planning on moving back to Germany soon, so I asked him to send me a postcard before he leaves Africa.


Here's what he has written (click to enlarge):
Encoded postcard from Madagascar


Have fun decoding it. ;-) (The resulting message is in German, by the way)

Monday, June 8, 2009

Compile-time-array in C++ using templates

We all know that it's possible to use templates for stuff that they were not quite invented for. In this fine example, an arbitrary number is tested for being prime at compile-time: here, see the first screenshot. A friend of mine now came up with the idea to solve this programming contest problem by pre-calculating the needed values using templates and filling a compile-time-array with them. Well, it ended that this was not a feasible solution for that specific task (because of the resulting sourcecode size), but I still wanted to give the compile-time-array a try. And that's what I came up with:

#include <iostream>

struct Null
{
};

template<int V, typename T = Null>
struct Element
{
typedef T Base;
static const int value = V;
};


template<typename Array, int Index>
struct At
{
static const int result =
At<
typename Array::Base,
Index - 1>::result;
};

template<typename Array>
struct At<Array, 0>
{
static const int result = Array::value;
};

int main()
{
using namespace std;
typedef Element<18, Element<23, Element<42> > > Array;
cout << At<Array, 0>::result << endl;
cout << At<Array, 1>::result << endl;
cout << At<Array, 2>::result << endl;
}

Pretty nice I'd say, huh? ;-)

Thanks to mandrill for pointing out that storing the index in Element, as I did in my first approach, is not needed at all.