Friday, November 19, 2010


The following program:

#include <iostream>
template <int N> struct X {
  enum {result = 2 * X<N-1>::result};};
template <>  struct X<0> {
  enum {result = 1};};
int main() {
  std::cout << X<16>::result << std::endl;
  return 0;

This is an example of metaprogramming with C++ templates. The code would be more clear if I changed the "X" to "Power". At the 1994 C++ Standardization Committee Erwin Unruh showed that compilers can do more complex calcuations. It was latter shown that C++ Template Metaprogramming is Turing Complete, meaning that it can compute anything that is computable. This is in theory. In practice, the C++ Standard recommends 17 levels of recursion. The above code uses 16. For a more detail on Template Metaprogramming see:

Reference: C++ Templates by David Vandevoorde and Nicolai M. Josuttis. Addison-Wesley, 2003, p. 302.

No comments:

Post a Comment