类模板的特化

类模板的特化

1 类模板的特化

    指定具体的匹配类型,简单如下所示

    (1)普通的类模板定义如下

template<class T>
class Test
{
public:
    ....
private:
    ....
}

    (2)特化的类模板

template<>     //这里<>中间是空的
class Test<int>   //跟在类名后的<>里指定具体的类型
{
public:
    ....
private:
    ....
}

2 类模板的半特化
    所谓半特化就是部分参数特化的模板。典型的如vector的bool类型时,调用的是半特化模板类。
    template<class _Alloc>        //0. <>非空,且指定_Alloc是泛化的类型
    class vector<_Bool, _Alloc>    //1. <>非空,指定当第一个参数是BOOL类型时,直接对应该模板
    在template关键字后面和class关键字后面的尖括号里都是非空的参数列表。

3 如果都能匹配时,应该选择“特化程度最高”的模板

#include <iostream>
using namespace std;

template <class T, class U>class C{
public:void f(){cout<<"Primary Template"<<endl; }
};
template <class U>class C<int, U>{
public:void f(){cout<<"int"<<endl;}
};
template <class T>class C<T, double>{
public:void f(){cout<<"double"<<endl;}
};
template <class T, class U>class C<T*, U>{
public:void f(){cout<<"T* is used"<<endl;}
};
template <class T, class U>class C<T, U*>{
public:void f(){cout<<"U* is used"<<endl;}
};
template<class T, class U>class C<T*, U*>{
public:void f(){cout<<"T* and U* is used"<<endl;}
};
template<class T>class C<T, T>{
public:void f(){cout<<"T = U is used"<<endl;}
};

int main()
{
	C<float, int>().f(); //"Primary Template"
	C<int, float>().f(); //"int"
	C<float, double>().f(); //"double"
	C<float*, float>().f(); //"T* is used"
	C<float, float*>().f(); //"U* is used"
	C<int*, float*>().f(); //"T* and U* is used"
	C<float, float>().f();  //"T = U is used"
	// C<float* float*> 冲突
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值