在模板递归中,也可以进行数值计算,这种计算由编译器来完成,故而会增加编译时间,但会减少运行时间,也会增加某种灵活性,之前记录了一个模板递归的例子,那个例子用于或许模板参数的类型信息,现在对那个例子做些简单的修改:通过数值的方式来记录模板递归的次数,代码如下:
template<typename T>
class CompoundT {
public:
enum { IsPtrT = 0, IsRefT = 0, IsArrayT = 0, IsFuncT = 0, IsPtrMemT = 0};
typedef T BaseT;
typedef T BottomT;
typedef CompoundT<void> ClassT;
static const int x=0;
};
这是基本模板,与《C++模板递归1》中的例子基本相同,只是增加了一个静态常量:static constant int x = 1;下面是它的一个特化:
template<typename T>
class CompoundT<T*> {
public:
enum { sPtrT = 1, IsRefT = 0, IsArrayT = 0, IsFuncT = 0, IsPtrMemT = 0};
typedef T BaseT;
typedef CompoundT<T> Temp;
typedef typename Temp::BottomT BottomT;
typedef CompoundT<void> ClassT;
static const int x = 1+Temp::x;
};
在这个特化版本中,递归主要体现在typedef CompoundT<T> Temp;最后用static constant int x = 1+Temp::x来记录递归的次数,与之前的例子相同,我们来观察一个CompoundT<int***>的递归结果,main函数如下:
int main(){
cout<<typeid(CompoundT<int**>::BottomanT).name()<<endl;
cout<<CompoundT<int**>::x<<endl;
return 0;
}
输出结果为:(注:i 表示int)
i
2
这说明模板递归了2次,为了定义CompoundT<int**>,首先递归定义了CompoundT<int*>,接着递归定义了CompoundT<int>,我们也可以看看没有递归的情况,比如定义CompoundT<int>,main函数修改如下:
int main(){
cout<<typeid(CompoundT<int>::BottomT).name()<<endl;
cout<<CompoundT<int>::x<<endl;
return 0;
}
输出结果为:
i
0