在泛型编程成,经常要比较元素的大小,但是有时候我们无法完成规定T 必须拥有比较的接口。
所以我们这里通过函数指定,T需要提供的比较内容
template<typename T>
int DefauletCMP(T a,T b)
{
if(a<b)
return -1;
if(a>b)
return 1;
if(a==b)
{
return 0;
}
}
template<typename T>
class Test
{
private:
T value;
typedef int (*CMP)(T a,T b);
CMP CMP1;
public:
Test()
{
CMP1=DefauletCMP<T>;
cout<<"init test"<<endl;
}
bool isBig(T a,T b)
{
if(CMP1(a,b)==0)
return true;
else
{
return false;
}
}
};
int main()
{
Test<int>he;
if(he.isBig(12,13))
cout<<"big"<<endl;
else
cout<<"littele"<<endl;
getchar();
}
CMP为比较接口,默认使用类operator <