Thread overview
D operator overloading. Why that way?
Sep 19, 2012
Hauleth
Sep 19, 2012
bearophile
Sep 19, 2012
monarch_dodra
September 19, 2012
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`.
September 19, 2012
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
September 19, 2012
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:
#1: This pre-supposes that opOpAssing returns something (not guaranteed), so it can't be made to default to this behavior.
#2: *SOME* object don't WANT to have a default opBinary, but they do have opOpAssign.
#3: Even then, maybe opBinary doesn't have the same semantics as 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.