Nilesh Kumar

Even the "perfect"-seeming has the most cunning imperfections.

C++ template metaprogramming : A simple example

, , ,

Template metaprogramming is used mainly to provide computation efficiency at compile time, i.e., suppose there is some computation that is being computed at translation time, then it can be optimized to be done at compile time using template metaprogramming in C++. Also, normally, template metaprograms are shorter in size. Let us understand this through an example :


#include <iostream>

template<long N>
class Fact
{   public:
        enum { result = N * Fact<N - 1>::result };
};
template<>
class Fact<0>
{   public:
        enum { result = 1 };
};

int main()
{   std::cout << Fact<10>::result;
    return 0;
}


The template metaprogramming works by recursive template instantaitions. The above code tries to compute factorial of a given number. And it does so at compile time. How it wroks is, you have to provide two rules for it to work. On rule that specifies how the recursion progresses and another which stops the recursion. Here, the two rules are as follows :

1. fact(n) = n * fact(n - 1)
2. fact(0) = 1;

Now, the first template
template<long N>
class Fact
{   public:
        enum { result = N * Fact<N - 1>::result };
};


confirms the first rule, and the second template
template<>
class Fact<0>
{   public:
        enum { result = 1 };
};


confirms the second rule.

This is the simplest example of a C++ template metaprogram. Another working example can be found here. The working copy of the above code can be found here.

For advanced uses, you can follow C++ Templates : Metaprograms. It is a chapter from the book C++ Templates : The Complete Guide.

Boost also provides a metaprogramming library. The likns are as follows :
1. The Boost MPL Library.
2. The Boost C++ Metaprogramming Library.

Libraries such as Blitz++, The Matrix Templte Library and POOMA make use of template metaprogramming.

The concept of C++ template metaprogramming was first made popular by Todd Veldhuizen in his paper Using C++ Template Metaprograms. Todd is one of the developer's of Blitz++.

The first documented example of a C++ template metaprogram was given by Erwin Unruh. His code can be seen here
.

ConScript : A browser extensionNew Linux kernel(v2.6.34) includes Ceph kernel client

Write a comment

New comments have been disabled for this post.

June 2012
M T W T F S S
May 2012July 2012
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30