模板为什么要特化,因为编译器认为,对于特定的类型,如果你能对某一功能更好的实现,那么就该听你的。

模板分为类模板与函数模板,特化分为全特化与偏特化。全特化就是限定死模板实现的具体类型,偏特化就是如果这个模板有多个类型,那么只限定其中的一部分。

先看类模板:

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;
};

那么下面3句依次调用类模板、全特化与偏特化:

	Test<double , double> t1(0.1,0.2);
	Test<int , char> t2(1,'A');
	Test<char, bool> t3('A',true);

而对于函数模板,却只有全特化,不能偏特化:

 

//模板函数
template<typename T1, typename T2>
void fun(T1 a , T2 b)
{
	cout<<"模板函数"<<endl;
}
 
//全特化
template<>
void fun<int ,char >(int a, char b)
{
	cout<<"全特化"<<endl;
}
 
//函数不存在偏特化:下面的代码是错误的
/*
template<typename T2>
void fun<char,T2>(char a, T2 b)
{
	cout<<"偏特化"<<endl;
}
*/
至于为什么函数不能偏特化,似乎不是因为语言实现不了,而是因为偏特化的功能可以通过函数的重载完成。

 

 

 

相关文章:

  • 2021-10-29
  • 2021-11-06
  • 2021-10-15
  • 2022-12-23
  • 2021-06-22
  • 2021-07-23
  • 2022-12-23
猜你喜欢
  • 2021-07-13
  • 2021-10-01
  • 2022-12-23
  • 2022-02-09
  • 2022-12-23
  • 2022-02-15
相关资源
相似解决方案