/* I've witten the following code example while reading the great book * "C++ Templates - The Complete Guide" * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002 * * After reading about template recursion and template metaprogramming * I've written this code example for calculating the nth Fibonacci * number. * * (C) Copyright Andre Alexander Bell 2003. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include template struct factorial { enum { result = N*factorial::result }; }; // Get the template recursion stop at these initial values template<> struct factorial<1> { enum { result = 1 }; }; template<> struct factorial<0> { enum { result = 1 }; }; int main() { // Factorials 0! to 4! // 1, 1, 2, 2*3=6, 4*6=24 // Now print out the 5 factorials with this template: std::cout << "0! = " << factorial<0>::result << std::endl; std::cout << "1! = " << factorial<1>::result << std::endl; std::cout << "2! = " << factorial<2>::result << std::endl; std::cout << "3! = " << factorial<3>::result << std::endl; std::cout << "4! = " << factorial<4>::result << std::endl; return 0; }