问题
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 >
,>
,>=
,<=
?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/32816843/are-any-c-operator-overloads-provided-automatically-based-on-others