上面对模板的特化进行了总结。那模板的偏特化呢?所谓的偏特化是指提供另一份模板定义式,而其本身仍为模板;也就是说,针对模板参数更进一步的条件限制所设计出来的一个特化版本。这种偏特化的应用在STL中是随处可见的。比如
1.测试代码:
#include <iostream>
using namespace std;namespace templateTest {//模版泛化template<typename T>class iterator_traits{public:iterator_traits() { cout << "模版泛化" << endl; }~iterator_traits() {}};//偏特化template<typename T>class iterator_traits<T*>{public:iterator_traits() { cout << "模版偏特化,特化常规指针" << endl; }~iterator_traits() {};};//偏特化template<typename T>class iterator_traits<const T*>{public:iterator_traits() { cout << "模版偏特化,特化const指针" << endl; }~iterator_traits() {}};//全特化template<>class iterator_traits<int>{public:iterator_traits() { cout << "模版全特化int类型" << endl; }~iterator_traits() {}};
};int main()
{templateTest::iterator_traits<int> t1; // 模版全特化int类型templateTest::iterator_traits<float> t2; // 模版泛化templateTest::iterator_traits<int*> t3; // 模版偏特化,特化常规指针templateTest::iterator_traits<const int*> t4; // 模版偏特化,特化const指针
}
2. 测试代码:
#include <iostream>
using namespace std;//泛化
template<class U, class T>
class Test
{
public:Test() { cout << "Test 泛化" << endl; }
};//偏特化
template<class T>
class Test<int, T>
{
public:Test() { cout << "Test 偏特化" << endl; }
};//全特化
template<>
class Test<int, char>
{
public:Test() { cout << "Test 全特化" << endl; }
};/*--------------------------------------------------*/template<typename T>
void max(const T& t1, const T& t2)
{cout << "模版函数泛化" << endl;}//其实函数模版不存在偏特化,只有全特化
template<>
void max<int>(const int& t1, const int& t2)
{cout << "模版函数全特化" << endl;
}void main()
{Test<int, int> t1; // Test 偏特化Test<float, int> t2; // Test 泛化Test<int, char> t3; // Test 全特化max(5, 10); // 模版函数特化max(5.5, 10.5); // 模版函数泛化
}