Wednesday, November 2, 2011

Recursive Templates

I have been thinking about doing a generic N dimension container and iterator template recently and started putting together some of the code for it. In order to make it work a good understanding of Template recursion is needed. Here is an trivial example

//built with mimggw g++ (gcc version 4.5.0 (GCC))
#include <iostream>

template <int n> 
struct Factorial
{
  enum { RET = Factorial<n-1>::RET * n };
}; 

template <>
struct Factorial<0>
{
  enum { RET = 1 };
}; 

int main()
{
  std::cout << Factorial<1>::RET << std::endl;
  std::cout << Factorial<2>::RET << std::endl;
  std::cout << Factorial<3>::RET << std::endl;
  std::cout << Factorial<4>::RET << std::endl;
}

1 comment:

  1. Many thanks for such a write-up. I undoubtedly cherished reading it.
    Administration Resume Templates

    ReplyDelete