模板的特化:
对某些类型进行特殊处理,下面是函数模板特化的一个例子:
template<class T>
bool IsEqual(T t1,T t2)
{
return t1==t2;
}
template<>
bool IsEqual(char* t1,char* t2)//IsEqual函数模板需要对char* 类型尽情特殊处理
{
return strcmp(t1,t2)==0;
}
类模板实现特化的原因和函数模板实现特化的原因相同.
类模板应用的一个例子:
template<class T1,class T2>
class Point_T
{
public:
T1 a;
T2 b;
Point_T():a(0),b(0){}
Point_T(T1 ta,T2 tb):a(ta),b(tb){}
Point_T<T1,T2>& operator=(Point_T<T1,T2> &pt);//赋值函数
friend Point_T<T1,T2>operator+(Point_T<T1,T2> &pt1,Point_T<T1,T2> &pt2);//重载
};
template<class T1,class T2>
Point_T<T1,T2>& Point_T<T1,T2>::operator=(Point_T<T1,T2> &pt)//赋值函数
{
this->a = pt.a;
this->b = pt.b;
return *this;
}
template<class T1,class T2>
Point_T<T1,T2> operator+(Point_T<T1,T2> &pt1,Point_T<T1,T2> &pt2)
{
Point_T<T1,T2> temp;
temp.a = pt1.a + pt2.a;
temp.b = pt1.b + pt2.b;
return temp;
}
template<class T1,class T2>
ostream& operator<<(ostream& out,Point_T<T1,T2>& pt)
{
out << "(" << pt.a << ",";
out << pt.b << ")";
return out;
}