I have implemented operator<
for a certain object.
Logically, if !(a < b)
and !(b < a)
it means a == b
.
Is this inferred automatically? Can I use ==
if I only implement <
?
C++ cannot infer this automatically for a couple of reasons:
operator<
, so the type may not necessarily define a operator<
.
operator==
cannot be automatically defined in terms of operator<
operator<
isn't required to compare its arguments. A programmer can define operators for their types to do almost anything to their arguments.
!(a < b) && !(b < a)
being equivalent to a == b
may not necessarily be true, assuming those operators are defined.If you want an operator==
function for your types, just define one yourself. It's not that hard :)
// For comparing, something like this is used
bool operator==(const MyType& lhs, const MyType& rhs)
{
// compare (or do other things!) however you want
}
// ... though it's not the only thing you can do
// - The return type can be customised
// - ... as can both of the arguments
const MyType& operator==(int* lhs, const MyType* const rhs)
{
return lhs;
}