模闆為什麼要特化,因為編譯器認為,對于特定的類型,如果你能對某一功能更好的實作,那麼就該聽你的。
模闆分為類模闆與函數模闆,特化分為全特化與偏特化。全特化就是限定死模闆實作的具體類型,偏特化就是如果這個模闆有多個類型,那麼隻限定其中的一部分。
先看類模闆:
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;
}
*/