如何选择 class 的 operator== 重载模板 operator==?
How to choose class's operator== overloading over the template operator==?
我已经使用模板和内联 class 方法为几种类型重载了 operator==
。但是当引用一个对象为lhs
时。将使用模板 operator==
重载。为什么不在 class 定义中重载 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 ==
是否可以强制编译器使用 class 中定义的重载?
Is it possible to force the compiler using the overloading defined
inside the class?
是,只需让operator==
重载一个const
合格的函数,这样它就会作用于[的const
对象=14=].
bool operator==(const Obj& rhs) const /* noexcept */
{
std::cout << "Obj == \n";
return a == rhs.a; // meaningful comparison
}
它选择模板重载,因为它是最佳匹配,它采用 const
对象。
作为旁注,请提供有意义的比较,如上所示。 See a demo
我已经使用模板和内联 class 方法为几种类型重载了 operator==
。但是当引用一个对象为lhs
时。将使用模板 operator==
重载。为什么不在 class 定义中重载 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 ==
是否可以强制编译器使用 class 中定义的重载?
Is it possible to force the compiler using the overloading defined inside the class?
是,只需让operator==
重载一个const
合格的函数,这样它就会作用于[的const
对象=14=].
bool operator==(const Obj& rhs) const /* noexcept */
{
std::cout << "Obj == \n";
return a == rhs.a; // meaningful comparison
}
它选择模板重载,因为它是最佳匹配,它采用 const
对象。
作为旁注,请提供有意义的比较,如上所示。 See a demo