Template metaprogramming is a programming technique where, at compile time, the compiler acts as a "virtual computer" and emits code optimized for a specific purpose or environment. Thus some calculations can take place at compile time rather than at runtime. Hence template metaprogramming uses binding much earlier than other programming techniques.
Often template metaprogramming is used in the C++ programming language. An example, taken from [1], shows how to use template metaprogramming. In C++ consider a factorial function written recursively as:
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
// factorial(4) == (4 * 3 * 2 * 1) == 24
// factorial(0) == 0! == 1
The factorial function can be substituted by the use of template metaprogramming:
template <int N>
struct Factorial {
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0> {
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
Using template metaprogramming means, that for example
Factorial<4>::value is calculated at compile time. The
call Factorial<x>::value, however, cannot be
calculated at compile time, unless x is known at compile
time.
When using template metaprogramming in C++, the programming technique is Turing Complete. For more information on template metaprogramming in general, see [2]
Benefits and drawbacks [1]
Bibliography
[1] Wikipedia, the free encyclopedia, Template metaprogramming, http://en.wikipedia.org/wiki/Template_metaprogramming
[2] Krzysztof Czarnecki, Ulrich W. Eisenecker, Generative Programming: Methods, Tools, and Applications, Addison-Wesley, ISBN 0-201-30977-7