【发布时间】:2021-10-19 22:31:55
【问题描述】:
我已经为几种类型重载了operator==,同时使用模板和内联类方法。但是当谈到一个对象的引用时,lhs。将使用模板operator== 重载。为什么不在类定义中重载operator==?
#include <iostream>
template <typename T0, typename T1>
bool operator==(const T0& lhs, const T1& rhs)
{
std::cout << "Template == " << std::endl;
return true;
}
struct Obj
{
std::int32_t a;
bool operator==(const Obj& rhs)
{
std::cout << "Obj == " << std::endl;
return true;
}
};
bool cmp(const Obj& obj) { return (obj == Obj{ 1 }); }
int main() {
Obj a{ 2 };
const Obj& b = a;
cmp(a);
cmp(b);
a == b;
b == a;
return 0;
}
此代码给出以下结果:
Template ==
Template ==
Obj ==
Template ==
是否可以使用类内部定义的重载来强制编译器?
【问题讨论】:
-
您的成员
operator==不是const成员函数,不能以const Obj作为其左侧来调用。 -
我真的希望你的实际模板函数没有你在这里展示的那么广泛。此外,您可以(并且应该)将
Obj::operator==函数设为const。 -
因为你还没有将成员函数限定为
const,所以模板版本更匹配。试试bool operator==(const Obj &rhs) const {return true;};。
标签: c++ function class templates operator-overloading