opIndexAddAssign? ...

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Fri Feb 9 11:54:39 PST 2007


Sean Kelly wrote:
> Lionello Lunesu wrote:
>> Manfred Nowak wrote:
>>> On writing the implementation of a map, where the Valuetype is a set, 
>>> I had to stop on recognizing, that only opIndexAssign is permitted.
>>>
>>> I.e.:
>>>   map[ key]+= element;
>>> has no possible overload.
>>>
>>> OpIndex delivers an rvalue and the only possibility to get an lvalue 
>>> is in conjunction with a plain assignment.
>>>
>>> Why arbitrary restrictions when the goal is to have great 
>>> expressiveness?
>>> -manfred
>>
>> opIndexAssign was needed because D has no "inout" return type. It's a 
>> hack, if you ask me.
> 
> It is a hack, but a useful one IMO.  For example, say I want to insert 
> an element in an AA only if the AA itself is used as an lvalue. ie.
> 
> auto x = myAA[key]; // return default value if not present
> myAA[key] = x;      // insert and assign
> 
> I'll admit that it would be much nicer if this worked for all applicable 
> operator overloads without requiring separate signatures for each, but 
> I'll take what I can get :-)

It's also useful for sparse vectors and matrices: you don't want to 
autoinsert stuff or throw when all you want is to read. Just return zero 
if it's not there.

Probably the principled thing to do is to allow two functions, one that 
returns lvalue and one that returns an rvalue, and have the compiler 
pick the appropriate one.


Andrei




More information about the Digitalmars-d mailing list