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.

1 comment:

  1. Need more time for an array value when the number is tested at compile time.
    Shopping Cart

    ReplyDelete