Search code examples
c++operator-overloadingcomparison-operators

Comparison operator overloading, why doesn't the compiler do the work?


Today I was implementing a datatype, in which I decided to overload the comparison operators. While doing this, a question popped into my head.

Why do I, as a programmer, have to define every single comparison operator, when all I do, is to define them in terms of '<' (see below)? - That is, why doesn't the compiler automatically generate these for me.

a == b    =>    !(a<b || b<a)
a != b    =>     (a<b || b<a)
a > b     =>    b < a
a >= b    =>    !(a < b)
a <= b    =>    !(b < a)

I do understand, that it is perfectly reasonable for performance reasons, to want to implement more than just '<'.

I know the obvious answer is, that it's because I can easily do it myself, but I do believe that compilers/language specifications should do whatever possible to ease using the language.


Solution

  • Define operator<() and operator==(), and

    #include <utility>
    using namespace std::rel_ops;
    

    Then all comparison operators are automatically defined. See the example provided by cppreference.com