模板分为类模板与函数模板,特化分为全特化与偏特化。全特化就是限定死模板实现的具体类型,偏特化就是如果这个模板有多个类型,那么只限定其中的一部分。
先看类模板:
[cpp]
template
template
class Test
{
public:
Test(T1 i,T2 j):a(i),b(j){cout<<"模板类"<
private:
T1 a;
T2 b;
};
template<>
class Test
{
public:
Test(int i, char j):a(i),b(j){cout<<"全特化"<
private:
int a;
char b;
};
template
class Test
{
public:
Test(char i, T2 j):a(i),b(j){cout<<"偏特化"<
private:
char a;
T2 b;
};
[cpp] view plaincopyprint template
class Test
{
public:
Test(T1 i,T2 j):a(i),b(j){cout<<"模板类"<
private:
T1 a;
T2 b;
};
template<>
class Test
{
public:
Test(int i, char j):a(i),b(j){cout<<"全特化"<
private:
int a;
char b;
};
template
class Test
{
public:
Test(char i, T2 j):a(i),b(j){cout<<"偏特化"<
private:
char a;
T2 b;
};
template
class Test
{
public:
Test(T1 i,T2 j):a(i),b(j){cout<<"模板类"<
private:
T1 a;
T2 b;
};
template<>
class Test
{
public:
Test(int i, char j):a(i),b(j){cout<<"全特化"<
private:
int a;
char b;
};
template
class Test
{
public:
Test(char i, T2 j):a(i),b(j){cout<<"偏特化"<
private:
char a;
T2 b;
};
那么下面3句依次调用类模板、全特化与偏特化:
[cpp] view plaincopyprint Test t1(0.1,0.2);
Test t2(1,'A');
Test t3('A',true);
[cpp] view plaincopyprint Test t1(0.1,0.2);
Test t2(1,'A');
Test t3('A',true);
Test t1(0.1,0.2);
Test t2(1,'A');
Test t3('A',true);
而对于函数模板,却只有全特化,不能偏特化:
[cpp] view plaincopyprint //模板函数
template
void fun(T1 a , T2 b)
{
cout<<"模板函数"<
}
//全特化
template<>
void fun(int a, char b)
{
cout<<"全特化"<
}
//函数不存在偏特化:下面的代码是错误的
/*
template
void fun(char a, T2 b)
{
cout<<"偏特化"<
}
*/
[cpp] view plaincopyprint //模板函数
template
void fun(T1 a , T2 b)
{
cout<<"模板函数"<
}
//全特化
template<>
void fun(int a, char b)
{
cout<<"全特化"<
}
//函数不存在偏特化:下面的代码是错误的
/*
template
void fun(char a, T2 b)
{
cout<<"偏特化"<
}
*/
//模板函数
template
void fun(T1 a , T2 b)
{
cout<<"模板函数"<
}
//全特化
template<>
void fun(int a, char b)
{
cout<<"全特化"<
}
//函数不存在偏特化:下面的代码是错误的
/*
template
void fun(char a, T2 b)
{
cout<<"偏特化"<
}
*/
至于为什么函数不能偏特化,似乎不是因为语言实现不了,而是因为偏特化的功能可以通过函数的重载完成。