1)模板类的特化
//1)类的特化
//泛化
template<class T, class K>
struct My
{
My(){cout<<"General Version\n";}
void test();
};
template<class T,class K> //泛化必须带所有泛化的参数
void My<T,K>::test()
{
cout<<"General Version: Test()\n";
}
//完全特化
template<> //类的完全特化,所有泛化参数均为指定数据类型,必须有template<>在class前,<>内为空,表示为完全特化
struct My<int, double>
{
My(){cout<<"Total Special Version\n";}
void test();
};
//template<> //注意这里对于完全特化的成员函数,不需要template<>了,直接有下面的函数即可
void My<int,double>::test()
{
cout<<"Total Special Version: Test()\n";
}
//偏特化
template<class T> //仅仅保留部分泛化参数,其他部分参数为特别指定的参数
struct My<T,double>
{
My(){cout<<"Partial Special Version\n";}
void test();
};
template<class T> //成员函数需要带template<泛化的参数>
void My<T,double>::test()
{
cout<<"Partial Special Version: Test()\n";
}
int main(int argc, _TCHAR* argv[])
{
My<short,int> a;
My<short,double> b;
My<int,double> c;
a.test();
b.test();
c.test();
return 0;
}
最后输出结果
General Version
Partial Special Version
Total Special Version
General Version: Test()
Partial Special Version: Test()
Total Special Version: Test()
2)模板类成员的特化
template<class T, class K>
struct Me
{
void We();
};
template<class T,class K> //泛化版本
void Me<T,K>::We(){cout<<"Member: General Version\n";}
//成员函数不能偏特化
//严格的来说,函数模板并不支持偏特化,但由于可以对函数进行重载,所以可以达到类似于类模板偏特化的效果
//这样就需要利用参数个数,参数顺序,const属性来进行重载了
//template<class T> //错误
//void Me<T,double>::We(){cout<<"Member: Partial Special Version\n";}
//完全特化
template<>
void Me<int,double>::We(){cout<<"Member: Total Special Version\n";}
int main(int argc, _TCHAR* argv[])
{
Me<short,int> e;
Me<short,double> f;
Me<int,double> g;
e.We();
f.We();
g.We();
return 0;
}
结果:
Member: General Version
Member: General Version
Member: Total Special Version
|