| metaprogramming/iteration/fac-2.cc - The factorial function defined as a function template - using a template int parameter. | Lecture 6 - slide 39 : 40 Program 2 |
// Factorial defined as a function template (4ed page 793).
// The input N is a templates parameter.
// C++11
#include <iostream>
template<int N>
constexpr int fac(){
return N * fac<N-1>();
}
template<> // A specialization for N = 1
constexpr int fac<1>(){
return 1;
}
int main(){
using namespace std;
// call of fac at compile time:
constexpr int res = fac<10>();
static_assert(res==3628800, "Value of fac<10> is incorrect");
cout << "fac(10) = " << res << endl; // fac(10) = 3628800
cout << "fac(5) = " << fac<5>() << endl; // fac(5) = 120
// attempt to call of fac at run time - not possible, however:
int i;
cout << "Enter i: ";
cin >> i;
cout << "fac(2*i) " << fac<2*i>() << endl; // Compile time error:
// the value of 'i' is not usable in a constant expression
}