函数模板接收对象作为参数时可能会遇到部分操作不能执行的情况,有以下两种解决方案:
1.在类的内部进行运算符重载
2.为函数模板写一个专门处理此类对象的重载
例如:以下代码写了一个比较函数的模板,但是直接传入两个Person对象进行比较是不可行的,于是可以采用重载运算符==或者重载函数模板本身,专门处理传入Person对象作为参数的情况
#include <iostream>
#include <string>
using namespace std;
//模板的局限性
template <typename T>
bool myCompare(T a,T b)
{
if (a == b)
{
return true;
}
else
return false;
}
class Person
{
friend bool operator==(Person& a, Person& b); //全局运算符==重载函数作友元以便访问私有成员
public:
Person() //默认构造函数-初始化属性值
{
m_Name = "";
m_Age = 0;
}
Person(string name, int age) //含参构造函数
{
this->m_Age = age;
this->m_Name = name;
}
//1.运算符重载,重载 == 运算符
//bool operator==(Person &a)
//{
// if (this->m_Age == a.m_Age && this->m_Name == a.m_Name)
// {
// return true;
// }
// else
// return false;
//}
protected:
private: //私有属性
string m_Name;
int m_Age;
};
bool operator==(Person& a, Person& b) //全局重载运算符==
{
if (a.m_Age == b.m_Age && a.m_Name == b.m_Name)
return true;
else
return false;
}
//2.写一个模板函数的特殊通道函数,专门处理特殊情况,其他大部分情况走主路,这个作为支路
//template<> bool myCompare(Person a, Person b) //模板的重载,传入参数确定为Person类型
//{
// if (a.m_Age == b.m_Age && a.m_Name == b.m_Name)
// {
// return true;
// }
// else
// return false;
//}
void test10()
{
Person p1 = { "Tom",18 };
Person p2 = { "Tom",19 };
//myCompare(p1, p2); //语法没有错误,但是运行报错
//有两种解决方法:1.运算符重载,重载==运算符
//2.写一个模板函数的特殊通道函数,专门处理特殊情况
int ret = myCompare(p1, p2);
if (ret)
{
cout << "p1==p2" << endl;
}
else
cout << "p1!=p2" << endl;
}
int main()
{
test10();
system("pause");
return 0;
}