Could I use operator == if I only implemented operator <?

Solution 1:

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;
}

Solution 2:

It cannot infer == from < because not all types are ordered, like std::complex. Is 2 + 3i > 1 + 4i or not?

Moreover even in types that are normally ordered you still can't infer the equality from > or <, for example IEEE-754 NaN

double n = std::numeric_limits<double>::quiet_NaN();

std::cout << "NaN == NaN: " << (n == n) << '\n';
std::cout << "NaN < NaN: " << (n < n) << '\n';
std::cout << "NaN > NaN: " << (n > n) << '\n';
std::cout << "NaN != NaN: " << (n != n) << '\n';

They'll all return false except the last one