Computations at compile time

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.

Leave a Reply