全特化

对于全特化类的所有参数,都与模板类的所有参数一一对应。
如下:
int 对应 T1,double 对应T2


#include<iostream>
using namespace std;

//模板类
template <class T1,class T2>
class base
{
public:
	void f(T1 a, T2 b)
	{
		cout << "模板类:";
		cout << a << " " << b << endl;
	}
};

//全特化类		int 对应 T1,double 对应T2
template<>
class base<int,double>
{
public:
	void f(int a, double b)
	{
		cout << "全特化类:";
		cout << a << " " << b << endl;
	}
};

int main()
{
	base<int,int> b1;
	cout << "1:" << endl;
	b1.f(1, 2);

	base<int,double> b2;
	cout << "2:" << endl;
	b2.f(1, 2.3);

	base<char, double> b3;
	cout << "3:" << endl;
	b3.f('a', 2.0);
}

输出:
1:
模板类:1 2
2:
全特化类:1 2.3
3:
模板类:a 2

可见,当满足全特化类时,优先调用全特化类,否则调用模板类

优先级:全特化类>模板类

偏特化类

偏特化类位于全特化类和模板类之间,只对模板类的部分参数进行显示声明
如下:
T1 无对应,默认为模板参数
T2对应double

#include<iostream>
using namespace std;

//模板类
template <class T1,class T2>
class base
{
public:
	void f(T1 a, T2 b)
	{
		cout << "模板类:";
		cout << a << " " << b << endl;
	}
};


//偏特化类
template<class T>
class base<T,double>
{
public:
	void f(T a, double b)
	{
		cout << "偏特化类:";
		cout << a << " " << b << endl;
	}
};

int main()
{
	base<int,int> b1;
	cout << "1:" << endl;
	b1.f(1, 2);

	base<int,double> b2;
	cout << "2:" << endl;
	b2.f(1, 2.3);

	base<char, double> b3;
	cout << "3:" << endl;
	b3.f('a', 2.0);
}

输出:
1:
模板类:1 2
2:
偏特化类:1 2.3
3:
偏特化类:a 2

可见,当满足偏特化类时,优先调用偏特化类,否则调用模板类

优先级:偏特化类>模板类

全特化类与偏特化类优先级

#include<iostream>
using namespace std;

//模板类
template <class T1,class T2>
class base
{
public:
	void f(T1 a, T2 b)
	{
		cout << "模板类:";
		cout << a << " " << b << endl;
	}
};

//全特化类
template<>
class base<int,double>
{
public:
	void f(int a, double b)  
	{
		cout << "全特化类:";
		cout << a << " " << b << endl;
	}
};

//偏特化类
template<class T>
class base<T,double>
{
public:
	void f(T a, double b)
	{
		cout << "偏特化类:";
		cout << a << " " << b << endl;
	}
};

int main()
{
	base<int,int> b1;
	cout << "1:" << endl;
	b1.f(1, 2);

	base<int,double> b2;
	cout << "2:" << endl;
	b2.f(1, 2.3);

	base<char, double> b3;
	cout << "3:" << endl;
	b3.f('a', 2.0);
}

输出:
1:
模板类:1 2
2:
全特化类:1 2.3
3:
偏特化类:a 2

对于模板类和全特化类、偏特化类共同存在时:

  • 如果满足全特化类,优先调用全特化类
  • 如果不满足全特化类,满足偏特化类,调用偏特化类
  • 如果都不满足,则调用模板类

可见,优先级为:全特化类>偏特化类>模板类

结论

类模板和函数模板都可以被全特化
类模板不能被重载
函数模板不可以被偏特化
类模板调用优先级为:全特化类>偏特化类>模板类

Q.E.D.