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;
}

3 comments:

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

    ReplyDelete
  2. coding classes for kids online I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here.

    ReplyDelete
  3. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. Guides

    ReplyDelete