Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 >,>,>=,<=?

like image 319
VoidStar Avatar asked Sep 28 '15 06:09

VoidStar


2 Answers

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.

like image 127
Cheers and hth. - Alf Avatar answered Sep 23 '22 07:09

Cheers and hth. - Alf


No.

C++ has no inference rules in the core language, so even defining say + it doesn't assume anything about +=... they're just (as far as the language goes) totally unrelated.

Consider that the << (left bit-shift operator) in the standard library has been overloaded to mean "output to stream"... just because of the look and of a sensible priority and associativity.

like image 37
6502 Avatar answered Sep 26 '22 07:09

6502