#include <cstdio> template<int N> class Factorial { public: static int const vl = N * Factorial<N - 1>::vl; }; template<> class Factorial<1> { public: static int const vl = 1; }; template<int N> class FactorialSum { public: static int const vl = Factorial<N>::vl + FactorialSum<N - 1>::vl; }; template<> class FactorialSum<1> { public: static int const vl = Factorial<1>::vl; }; void main() { int const N = 7; printf("%d的阶乘:%d ", N, Factorial<N>::vl); printf("%d的阶乘之和:%d ", N, FactorialSum<N>::vl); }
参考:http://www.cnblogs.com/winter-cn/archive/2009/09/05/1561094.html