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

淺唱寂寞╮ 提交于 2019-12-10 17:44:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!