C++模板递归2

在模板递归中,也可以进行数值计算,这种计算由编译器来完成,故而会增加编译时间,但会减少运行时间,也会增加某种灵活性,之前记录了一个模板递归的例子,那个例子用于或许模板参数的类型信息,现在对那个例子做些简单的修改:通过数值的方式来记录模板递归的次数,代码如下:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值