#include <iostream>
#include <string>
using namespace std;
//模板函数的局限性:
class Person
{
public:
Person(int age, string name)
{
this->m_Age = age;
this->m_Name = name;
}
string m_Name;
int m_Age;
};
template<class T>
bool myCompare(T &a, T &b)
{
if (a == b) {
return true;
}
else {
return false;
}
}
void test01()
{
int a = 10;
int b = 20;
int res = myCompare(a, b);
cout << "res=" << res << endl;
Person p1(10,"Tom");
Person p2(20,"Jerry");
//int res2 = myCompare(p1, p2);//不能进行比较;
//cout << "res2=" << res2 << endl;
}
//通过具体化自定义数据类型,来解决上述问题:
//相当于告诉编译器。当T为Person类型时,就再走这一条路;
//语法: template <> 返回值 函数名<类型>(参数);
template<> bool myCompare<Person>(Person &a, Person &b)
{
if (a.m_Age == b.m_Age) {
return true;
}
else {
return false;
}
}
void test02()
{
Person p1(10, "Tom");
Person p2(20, "Jerry");
int res2 = myCompare(p1, p2);//不能进行比较;
cout << "res2=" << res2 << endl;
}
//此时则可运行;
//优先匹配具体化的模板函数;
int main()
{
test01();
test02();
return 0;
}
函数模板不能解决全部问题,此时需要具体化