主模板的全特化、偏特化,包括引用、指针、自定义类、自定义模板嵌套的特化
#include <iostream>
using namespace std;
// 主模板
template <class T1, class T2>
class A
{
public:
void function(T1 value1, T2 value2)
{
cout << "value1 = " << value1 << endl;
cout << "value2 = " << value2 << endl;
}
};
template <>
class A<int, double>
{ // 类型明确化,全特化类
public:
void function(int value1, double value2)
{
cout << "int value1 = " << value1 << endl;
cout << "double value2 = " << value2 << endl;
}
};
template <class T>
class A<int, T>
{ // 类型部分明确化,偏特化类
public:
void function(int value1, T value2)
{
cout << "int value1 = " << value1 << endl;
cout << "double value2 = " << value2 << endl;
}
};
class MyType
{ // 自定义类型
public:
char ch;
MyType(char _ch) : ch(_ch) {}
};
template <>
class A<int, MyType>
{ //绝对类型特化,两个模板类型被特化为一个普通类型和一个自定义的数据类型
public:
void function(int value1, MyType value2)
{
cout << "int value1 = " << value1 << endl;
cout << "double value2 = " << value2.ch << endl;
}
};
template <class T1, class T2>
class A<T1 *, T2 *>
{ // 指针类型特化
public:
void function(T1 *pValue1, T2 *pValue2)
{
cout << "int value1 = " << *pValue1 << endl;
cout << "double value2 = " << *pValue2 << endl;
}
};
template <class T1, class T2>
class A<T1 &, T2 &>
{ // 引用类型特化
public:
void function(T1 &pValue1, T2 &pValue2)
{
cout << "int value1 = " << pValue1 << endl;
cout << "double value2 = " << pValue2 << endl;
}
};
template <class T>
class Number
{
public:
T value;
Number(T v) : value(v) {}
};
template <class T1, class T2>
class A<Number<T1>, Number<T2>>
{ // 模板类型变成另外一个模板类
public:
void function(Number<T1> n1, Number<T2> n2)
{
cout << "int value1 = " << n1.value << endl;
cout << "double value2 = " << n2.value << endl;
}
};
int main()
{
// 全特化
A<int, double> a;
a.function(12, 12.21);
// 偏特化
A<int, char> b;
b.function(12, 'b');
// 绝对特化
A<int, MyType> c;
MyType my_type('m');
c.function(12, my_type);
int p1 = 1;
char p2 = 'p';
// 指针特化
A<int *, char *> d;
d.function(&p1, &p2);
// 引用特化
A<int &, char &> e;
e.function(p1, p2);
// 模板嵌套特化
A<Number<int>, Number<double>> f;
f.function(1, 12.21);
return 0;
}