metaprogramming/iteration/fac-3.cc - The factorial function programmed in struct - with recursion. | Lecture 6 - slide 39 : 40 Program 3 |
// Factorial defined as a static int member in a struct. // Can only be used a compile time // Does not rely on C++11 facilities. #include <iostream> // Defining and holding the factorial value in a static int member. template<int N> struct Fac{ static const int value = N * Fac<N-1>::value; }; template<> // A specialization for N = 1 struct Fac<1>{ static const int value = 1; }; int main(){ using namespace std; // Call of fac at compile time: const int res = Fac<10>::value; cout << "fac(10) = " << res << endl; // fac(10) = 3628800 cout << "fac(5) = " << Fac<5>::value << endl; // fac(5) = 120 // Fac cannot be called with run time input. }