函数模板特化
好处:
针对特殊类型,提供优化的函数
类模板的特化
"你可以用模板实参来特化类模板,和函数模板的重载类似,通过特化类模板,你可以优化基于某种特定类型的实现。或者克服某种特定类型在实例化类模板时出现的不足。 另外如果要特化一个类模板,你还要特化该类模板的所有成员函数。虽然也可以只特化某个成员函数,但这个做法并没有特化整个类,也就没有特化整个类模板。
"
使用类模板物化的好处:
当智能指针的类型为int
时就不用调用析构函数了。
类模板的局部特化
类模板的局部特化又称为偏特化。
注意偏特化代码是这段
template<class T>
class Compare<T*>
...........................
http://www.cppblog.com/SmartPtr/archive/2007/07/04/27496.aspx
#include <iostream>
using namespace std;
// general version
template<class T>
class Compare
{
public:
static bool IsEqual(const T& lh, const T& rh)
{
return lh == rh;
}
};
// specialize for float
template<>
class Compare<float>
{
public:
static bool IsEqual(const float& lh, const float& rh)
{
return abs(lh - rh) < 10e-3;
}
};
// specialize for double
template<>
class Compare<double>
{
public:
static bool IsEqual(const double& lh, const double& rh)
{
return abs(lh - rh) < 10e-6;
}
};
// specialize for T*
template<class T>
class Compare<T*>
{
public:
static bool IsEqual(const T* lh, const T* rh)
{
return Compare<T>::IsEqual(*lh, *rh);
}
};
void main()
{
// int
int i1 = 10;
int i2 = 10;
bool r1 = Compare<int>::IsEqual(i1, i2);
// float
float f1 = 10;
float f2 = 10;
bool r2 = Compare<float>::IsEqual(f1, f2);
// double
double d1 = 10;
double d2 = 10;
bool r3 = Compare<double>::IsEqual(d1, d2);
// pointer
int* p1 = &i1;
int* p2 = &i2;
bool r4 = Compare<int*>::IsEqual(p1, p2);
}
下面这个例子是我自己写的
结果
T -- T
2
T -- int
3
int --- int
9
通过这两个例子,就能清楚地明白类模板的局部特化的好处了。