C++ Template Metaprogramming

8 views
Skip to first unread message

Nilu

unread,
May 22, 2010, 6:01:55 AM5/22/10
to nextgen_engg
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 at http://codepad.org/yoVMNlXH . The
working copy of the above code can be found at http://codepad.org/LaZszEhR
.

For advanced uses, you can follow http://www.informit.com/articles/article.aspx?p=30667&seqNum=5&rll=1
. It is a chapter from the book C++ Templates : The Complete Guide.
Link for the same :
http://books.google.com/books?id=EotSAwuBkJoC&printsec=frontcover&dq=c%2B%2B+templates+the+complete+guide&ei=YqP3S9yDNZvSkgTl46XmCQ&cd=1#v=onepage&q&f=false
.

Boost also provides a metaprogramming library. The likns are as
follows :
1. http://www.boost.org/doc/libs/1_43_0/libs/mpl/doc/index.html
2. http://www.boost.org/doc/libs/1_31_0/libs/mpl/doc/paper/mpl_paper.pdf

Libraries such as Blitz++, 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 at http://codepad.org/MJzELxpQ

Regards,
Nilesh
Reply all
Reply to author
Forward
0 new messages