- 模板特化按对象类型(类和全局函数)分为两种: 类模板的特化和全局模板函数的特化;
- 按特化的类型分全特化和偏特化(也就是多个模板参数可以选定只特化一个或者多个),全局模板函数的特化不支持偏特化;
- 全局模板函数的特化需要关注几个重要元素函数返回值 函数名 形参类型、个数和顺序,eg:
template T max_(const T &, const T &) - 类模板的特化需要关注几个重要元素类名,形参类型和个数,形参的顺序倒不重要了;
- 模板特化,任何针对模板参数进一步进行条件限制设计的特化版本。《泛型思维》
全特化就是全部特化,即针对所有的模板参数进行特化。《c++ primer》
偏特化就是部分特化,即针对部分模板参数进行特化。《c++ primer》
全特化和偏特化的定义不是很严格,所以有的时候不容易让人理解。
#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()
{
}
};
};
//泛化
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()
{
templateTest::iterator_traits<int> t1;
templateTest::iterator_traits<float> t2;
templateTest::iterator_traits<int *> t3;
templateTest::iterator_traits<const int *> t4;
Test<int, int> t5;
Test<float, int> t6;
Test<int, char> t7;
max(5, 10);
max(5.5, 10.5);
system("pause");
}
输出如下:
模版全特化int类型
模版泛化
模版偏特化,特化常规指针
模版偏特化,特化const指针
Test 偏特化
Test 泛化
Test 全特化
模版函数特化
模版函数泛化
请按任意键继续. . .