Operator overloading -- lets collect some use cases

Don nospam at nospam.com
Wed Dec 31 07:25:12 PST 2008


Stewart Gordon wrote:
> Don wrote:
>> Don wrote:
>>> There's been some interesting discussion about operator overloading 
>>> over the past six months, but to take the next step, I think we need 
>>> to ground it in reality. What are the use cases?
>>>
>>> I think that D's existing opCmp() takes care of the plethora of 
>>> trivial cases where <, >= etc are overloaded. It's the cases where 
>>> the arithmetic and logical operations are overloaded that are 
>>> particularly interesting to me.
>>>
>>> The following mathematical cases immediately spring to mind:
>>> * complex numbers
>>> * quaternions
>>> * vectors
>>> * matrices
>>> * tensors
>>> * bigint operations (including bigint, bigfloat,...)
>>> I think that all of those are easily defensible.
>>>
>>> But I know of very few reasonable non-mathematical uses.
>>> In C++, I've seen them used for iostreams, regexps, and some stuff 
>>> that is quite frankly bizarre.
>>>
>>> So, please post any use cases which you consider convincing.
>>
>> Some observations based on the use cases to date:
>> (1)
>> a += b is ALWAYS a = a + b (and likewise for all other operations).
>> opXXXAssign therefore seems to be a (limited) performance 
>> optimisation. The compiler should be allowed to synthesize += from +. 
>> This would almost halve the minimum number of repetitive functions 
>> required.
> <snip>
> 
> I thought it did.  I must've been imagining it.  But the really silly 
> thing is that, for classes, it seems you can't even make a += b behave 
> as a = a + b, i.e. reassigning the reference a.  Consequently, having 
> op= on an immutable big integer class is out of the question. 

Yuck! That's good to know.

There was
> a proposal that I supported a while back - see
> http://www.digitalmars.com/d/archives/digitalmars/D/announce/DMD_0.177_release_6132.html#N6150 
> 
> and followups.  The same would work for opXXXAssign (albeit not static).
> 
> In short, the way it could be made to work is:
> 
> - If a.opAddAssign(b) exists and returns something, make a += b 
> equivalent to a = a.opAddAssign(b)
> - If a.opAddAssign(b) exists and returns void, make a += b equivalent to 
> (a.opAddAssign(b), a)
> (this is a bit like another of my too-much-ignored proposals
> http://www.digitalmars.com/d/archives/digitalmars/D/10199.html )
> - Otherwise, make a += b equivalent to a = a + b.
> 
> Of course, the expression represented by a would be evaluated only once 
> in each case.
> 
> Stewart.



More information about the Digitalmars-d mailing list