1. 计算给点整数的指定次方
template <int Base, int Exponent>
class XY {
public:
enum { result = Base * XY<Base, Exponent - 1>::result };
};
// 用于终结递归的局部特化
template <int Base>
class XY<Base, 0> {
public:
enum { result = 1 };
};
void test_6(){
std::cout <<" result : " << XY<5,4>::result << std::endl;
}
2. 计算阶乘
// 递归模板元
template <unsigned n>
struct Factorial {
// Factorial<n> is times of the value of Factorial<n-1>
enum { value = n * Factorial<n-1>::value };
};
// special case: the value of Factorial<0> is 1
template<>
struct Factorial<0> {
enum { value = 1 };
};
void test3(){
std::cout << Factorial<5>::value << std::endl;
}
3. // 递归模板元
template <unsigned n>
struct Factorial {
// Factorial<n> is times of the value of Factorial<n-1>
enum { value = n * Factorial<n-1>::value };
};
// special case: the value of Factorial<0> is 1
template<>
struct Factorial<0> {
enum { value = 1 };
};
void test3(){
std::cout << Factorial<5>::value << std::endl;
}