A possible solution for the opIndexXxxAssign morass

Don nospam at nospam.com
Wed Oct 14 23:58:51 PDT 2009


Andrei Alexandrescu wrote:
> Don wrote:
>> Well timed. I just wrote this operator overloading proposal, part 1.
>> http://www.prowiki.org/wiki4d/wiki.cgi?LanguageDevel/DIPs/DIP7
>> I concentrated on getting the use cases established.
> 
> I'm not sure multiplication is generally commutative (e.g. in linear 
> algebra it isn't). So why should a * x be interchangeable with x * a?

It only applies a is an int or real. Its purpose is to allow 
constant-folding in the compiler front-end (specifically, when a is a 
manifest constant).

> Also, the much-discussed identity:
> 
> x @= y    <-->    x = x @ y
> 
> is difficult to enforce statically in practice. I think some types would 
> want to define both to achieve good efficiency. It would be hard for the 
> compiler to render one unnecessary or to prove that the two are equivalent.

Yes, it could not be enforced. But note that there would be no ambiguity 
as to which should be used in any given expression.
I would propose that the opXXXAssign() variants should exist *only* for 
performance optimisation, and be completely divorced from the "+=" 
syntax (effectively, += would be discarded after the parsing step).
My ancient Bugzilla proposal actually included opSubAssign() and 
opSubAssign_r() for  x = x - y; and x = y - x;
If   the x @= y    <-->    x = x @ y transformations became legal, this 
would allow unnecessary temporaries to be completely eliminated.

The suggested transformation would be that x = x + y would be 
transformed into x.opAddAssign(y) whenever it exists, and x = y + x 
would become x.opAddAssign_r(y)
The transformations would therefore be entirely predictable.

It would make Numpy-style arithmetic impossible (where z=x; x+=y; 
modifies z, but z = x; x = x+y; does not modify z (under this proposal, 
the second would be transformed into the first)).

Tightly defined semantics improve performance and reduce the potential 
for abuse. But, there are existing libraries/techniques which depend on 
C++'s cavalier, "anything goes" attitude to operator overloading. Are we 
able to sacrifice them?



More information about the Digitalmars-d mailing list