Operator overloading -- lets collect some use cases

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Dec 30 23:35:27 PST 2008


Don wrote:
> Weed wrote:
>> Frits van Bommel пишет:
>>> Don wrote:
>>>> Frits van Bommel wrote:
>>>>> Don wrote:
>>>>>> A straightforward first step would be to state in the spec that "the
>>>>>> compiler is entitled to assume that X+=Y yields the same result as
>>>>>> X=X+Y"
>>>>> That doesn't hold for reference types, does it?
>>>> I thought it does? Got any counter examples?
>>> For any class type, with += modifying the object and + returning a 
>>> new one:
>>
>> The += operator too should return the object (usually "this")
> 
> ALWAYS 'this'. It's another feature of operator overloading which is 
> redundant.

Well as well as you yourself noticed in an older discussion, 
consistently returning "this" clashes with expression templates. But 
then IMHO the existence of "auto" makes it imperative that we find a 
better solution than expression templates.

Changing gears, let's work on a simple example. Say we define a struct 
Vector and we want the following to be as fast as hand-coded:

Vector a, b, c;
double alpha = 0.5;
...
a = b + alpha * c;

The reference hand-coded implementation is:

enforce(a.length == b.length && b.length == c.length);
foreach (i; 0 .. a.length)
{
     a[i] = b[i] + alpha * c[i];
}

All right, let's do this with operator overloading :o). Ideas? I have a 
couple, but I don't want to introduce bias.


Andrei



More information about the Digitalmars-d mailing list