/* 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 nth_fibonacci { enum { result = nth_fibonacci::result + nth_fibonacci::result }; }; // Get the template recursion stop at these initial values template<> struct nth_fibonacci<1> { enum { result = 1 }; }; template<> struct nth_fibonacci<0> { enum { result = 1 }; }; int main() { // Fibonacci numbers 0 to 6 // 1, 1, 1+1=2, 1+2=3, 2+3=5, 3+5=8, 5+8=13 // Now print out the 6th number with this template: std::cout << "6th-Fibonacci-number: " << nth_fibonacci<6>::result << std::endl; return 0; }