Computations at compile time

August 13th, 2009 § Leave a Comment

The C++ template mechanism is a very powerful tool. Besides its great ability of code generation, it can also be used to make useful computations at compile time. Let us introduce such an example.

Consider the following show case:

#include <iostream>
using std::cout;

template <unsigned long N>
struct factorial {
    static const unsigned long num = N * factorial<N-1>::num;
};

template <> // template specialization
struct factorial<0> {
    static const unsigned long num = 1;
};

int main () {
    cout << factorial<9>::num;
    return 0;
}

This approach allows us to calculate the factorial of any number in compile time, having it constant at execution time. It is of course possible to think of many more uses for this technique.

Tagged: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What’s this?

You are currently reading Computations at compile time at 0x.

meta