// IfThenElse.hpp
1 #pragma once
2
3 template<bool C>, typename Ta, typename Tb>
4 class IfThenElse;
5
6 template<typename Ta, typename Tb>
7 class IfThenElse<true, Ta, Tb>
8 {
9 public:
10 typedef Ta ResultT;
11 };
12
13 template<typename Ta, typename Tb>
14 class IfThenElse<false, Ta, Tb>
15 {
16 public:
17 typedef Tb ResultT;
18 };
//这个IfThenElse模板估计以后要经常用到
// Sqrt.hpp
#pragma once
#include "IfThenElse.hpp"
1 template<int Num, int LOW = 0, int HIGH = Num>
2 class Sqrt
3 {
4 public:
5 // calculate mid value
6 enum
7 {
8 mid = (LOW + HIGH + 1) / 2,
9 };
10
11 // 二分法
12 typedef typename IfThenElse< (Num < mid * mid)
13 , Sqrt<Num, LOW, mid - 1>
14 , Sqrt<Num, mid, HIGH>
15 >::ResultT SubT;
16
17 enum
18 {
19 result = SubT::result;
20 };
21 };
22
23 template<int Num, int M>
24 class Sqrt<Num, M, M> // 偏特化,作为终止
25 {
26 public:
27 enum
28 {
29 result = M,
30 };
31 };
让我们测试一下
std::cout<< "Sqrt<25>::result = " << Sqrt<25>::result << std::endl;
1 template<int Num, int LOW = 0, int HIGH = Num>
2 class Sqrt
3 {
4 public:
5 // calculate mid value
6 enum
7 {
8 mid = (LOW + HIGH + 1) / 2,
9 };
10
11 // 二分法
12 typedef typename IfThenElse< (Num < mid * mid)
13 , Sqrt<Num, LOW, mid - 1>
14 , Sqrt<Num, mid, HIGH>
15 >::ResultT SubT;
16
17 enum
18 {
19 result = SubT::result;
20 };
21 };
22
23 template<int Num, int M>
24 class Sqrt<Num, M, M>
posted on 2006-10-27 09:45
七星重剑 阅读(1128)
评论(3) 编辑 收藏 引用 所属分类:
PL--c/c++