模板的通用性并不是万能的
正常情况:
//对比两个数据是否相等
template<class T>
bool myCom(T& a, T& b)
{
if (a == b)
{
return true;
}
else
{
return false;
}
}
void test01()
{
int a = 10;
int b = 20;
bool ret = myCom(a, b);
if (ret)
{
cout << "a==b" << endl;
}
else
{
cout << "a != b" << endl;
}
}
结果:
如果我们这样:定义一个类
class Person
{
public:
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void test02()
{
Person p1("Tom", 10);
Person p2("Tom", 10);
bool ret = myCom(p1, p2);
if (ret)
{
cout << "p1==p2" << endl;
}
else
{
cout << "p1 != p2" << endl;
}
}
此时就会报错。
解决办法:
//利用具体化Person的版本实现代码,具体化优先调用
template<> bool myCom(Person & a, Person& b)
{
if (a.m_name == b.m_name && a.m_age == b.m_age)
{
return true;
}
else
{
return false;
}
}