Search code examples
c++operator-overloadingcompiler-generated

Are any C++ operator overloads provided automatically based on others?


Say I'm writing an int wrapper and need to provide every single operator overload. Must the author list out every single one, or can it auto-generate any based on what the author has provided? Can/does the compiler infer any new auto-defined operators from existing ones?

If I define operator==, does it give me an operator!= automatically? Or vice-versa?

If I define operator++(), do I get operator++(int) for free? Or vice versa?

How about the += type business? Can it combine existing definitions of operator+ with operator= to generate operator+=? In theory it should be possible but does it?

Same question for >= to <, etc, or do I have to fully list out definitions for >,>,>=,<=?


Solution

  • In the core language the various operators are independent. Some are defined in terms of others, but if overload resolution for an operator invocation fails then there is no attempt to express that invocation in terms of other operators. When that's desired it can easily be expressed by the programmer (the opposite, turning off such machinery, would probably be more difficult).

    There is a set of relational operator overloads in std::rel_ops that client code can use, defined in terms of < and ==.

    You can easily write a mixin-class that provides relational operators in terms of < and ==, or in terms of a tri-valued compare function. That was the original motivation for the Curiously Recurring Template Pattern, called the Barton-Nackman trick.