cplusplus.co.il

Computations at compile time

Posted on: 13/08/2009

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 ofcourse possible to think of many more uses for this technique.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: