模板的特化:函数模板的特化和类模板的特化
当函数模板或者类模板需要对一些特殊的类型做特殊处理的时候,需要用到c++中模板的特化机制。
比如如下代码,模板ret_max中两个参数t1和t2,可以是多个类型,int,double,。如果需要对特殊的类型如下面代码的char *类型,做特殊的处理,就是里面实现的功能不一样。就可以使用如下的方法。
#if 1
template <class T>
bool ret_max(T t1, T t2)
{
cout << "the fun:ret_max(T t1, T t2) :";
return (t1 > t2) ? t1 : t2;
}
#endif
template <> bool ret_max<char *>(char *str1, char *str2)
{
cout << "the fun:ret_max(char *str1, char* str2) :";
return strcmp(str1, str2) == 0;
}
类模板的特化也是一样,具体的格式如下:
// (1)
template <class A, class B, class C>
class T {};
//(2)
template <>
class T<float, long, int>{};
//(3)
template <class B, class C>
class T<int, B, C>{};
如果编译器遇到是T <float, long, i