使用枚举变量的方式:
- #include <iostream>
- using namespace std;
- template<int T>
- struct factorial {
- enum { value = T * factorial<T - 1>::value };
- };
- template<>
- struct factorial<0> {
- enum { value = 1 };
- };
- int main()
- {
- cout << factorial<6>::value << endl;
- return 0;
- }
使用静态变量方式:
- using namespace std;
- template<int T>
- class factorial {
- public: static const int value = T * factorial<T - 1>::value ;
- };
- template<>
- class factorial<0> {
- public: static const int value = 1 ;
- };
- int main()
- {
- cout << factorial<10>::value << endl;
- return 0;
- }
参考:
http://bbs.chinaunix.net/thread-199443-1-1.html