模板元函數 收集中

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;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章