www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - D operator overloading. Why that way?

reply "Hauleth" <lukasz niemier.pl> writes:
Is there any reason to allow overload `op=`? IMHO it should be 
left illegal and should be interpreted always as `a = a op b`. It 
will be simpler and less confusing.

Also why `opEquals` is independent from `opCmp`? Once again 
`opEquals` should be removed and equality will be provided by 
`opCmp() == 0`.
Sep 19 2012
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Hauleth:

 Is there any reason to allow overload `op=`? IMHO it should be 
 left illegal and should be interpreted always as `a = a op b`. 
 It will be simpler and less confusing.
The increase of complexity and confusion is small.
 Also why `opEquals` is independent from `opCmp`?
A Complex number defines equality but not comparisons: https://raw.github.com/D-Programming-Language/phobos/master/std/complex.d Sometimes computing equality is faster than comparisons, so better have both.
 Once again `opEquals` should be removed and equality will be 
 provided by `opCmp() == 0`.
I'd like the opposite: more freedom to be able to define "<" but not "<=". Bye, bearophile
Sep 19 2012
prev sibling parent "monarch_dodra" <monarchdodra gmail.com> writes:
Sorry for mixing your reply, but I want to answer your second 
question first.

On Wednesday, 19 September 2012 at 14:39:20 UTC, Hauleth wrote:
 Also why `opEquals` is independent from `opCmp`? Once again 
 `opEquals` should be removed and equality will be provided by 
 `opCmp() == 0`.
Because some types can't be logically ordered. For example, coordinates. It makes no sense to give coordinates a logical order, but comparing them for equality does.
 Is there any reason to allow overload `op=`? IMHO it should be 
 left illegal and should be interpreted always as `a = a op b`. 
 It will be simpler and less confusing.
Arguably, this default would be much too expensive. If anything, it would work the other way around, where: "opBinary" is replaced by "{auto temp = a; a += b; return a;}" BUT: guaranteed), so it can't be made to default to this behavior. do have opOpAssign. the above implementation. So it is not possible to make one default on the implementation of the other So yeah, long story short, you can implement opOpAssing, and then implementation of opBinary should be trivial, but it remains the dev's job to choose if or if not he wants the op.
Sep 19 2012