Eyzuky Eyzuky - 1 year ago 28
C++ Question

Can I use operator == if I only implemented operator < in c++?

I have implemented operator < for a certain object.
Logically, if

!(a < b)
and
!(b < a)
it means
a == b
.
Does c++ infer this automatically? Can I use
==
if I only implemented
<
?

Answer Source

C++ cannot infer this automatically for a couple of reasons:

  1. It doesn't make sense for every single type to be compared with operator<, so the type may not necessarily define a operator<.
    • This means that operator== cannot be automatically defined in terms of operator<
  2. operator< isn't required to compare its arguments. A programmer can define operators for their types to do almost anything to their arguments.
    • This means that your statement about !(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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download