在上一篇博客中,我们介绍了模板的全特化。这里,我们将继续介绍模板的偏特化。偏特化包括两种,个树的偏和范围的偏。
个数的偏
如果模板参数有两个,你想绑定其中一个,这就实现了模板的偏特化。但需要注意的是,要按顺序从左到右绑定模板参数,不能跳跃式绑定第一三五个模板参数。
template<typename T, typename Alloc=...>
class vector
{
...
};
template<typename Alloc=...>
class vector<bool, Alloc> //绑定了T
{
...
};
范围的偏
如果我们设计接收任意类型的T,要是我们缩小接收范围为指向任意类型T的指针,这就是模板的偏特化。
template<typename T>
class C
{
...
};
template<typename T>
class C<T*>
{
...
};
#include<iostream>
using std::cout;
using std::endl;
template<typename T1, typename T2>
class Test
{
public:
Test(T1 i, T2 j)
: a(i), b(j)
{
cout << "模板类" << endl;
}
private:
T1 a;
T2 b;
};
template<> //全特化,模板参数都被指定,故此处<>为空
class Test<int, char>
{
public:
Test(int i, char j)
: a(i), b(j)
{
cout << "全特化" << endl;
}
private:
int a;
char b;
};
template<typename T2> //由于指定了一部分参数,剩下未指定的参数需在参数列表中
class Test<char, T2>
{
public:
Test(char i, T2 j)
: a(i), b(j)
{
cout << "个数偏特化" << endl;
}
private:
char a;
T2 b;
};
template<typename T1, typename T2>
class Test<T1*, T2*>
{
public:
Test(T1* i, T2* j)
: a(i), b(j)
{
cout << "指针偏特化" << endl;
}
private:
T1* a;
T2* b;
};
template<typename T1, typename T2> //同理这也是范围上的偏特化
class Test<T1 const, T2 const>
{
public:
Test(T1 i,T2 j)
:a(i),b(j)
{
cout<<"const偏特化"<<endl;
}
private:
T1 a;
T2 b;
};
int main()
{
int a;
Test<double, double> t1(0.1,0.2);
Test<int, char> t2(1, 'A');
Test<char, bool> t3('B', true);
Test<int*, int*> t4(&a, &a);
Test<int const, int const> t5(3,6);
return 0;
}