My Kingdom For ...

Bill Baxter dnewsgroup at billbaxter.com
Thu Feb 21 11:34:45 PST 2008


Jarrett Billingsley wrote:
> "Robert Fraser" <fraserofthenight at gmail.com> wrote in message 
> news:fpjuh5$uai$1 at digitalmars.com...
>> Darryl Bleau wrote:
>>> opIndexConcat
>>> opIndexConcatAssign
> 
> // Contrived, but shows the issue.
> struct IntArray
> {
>     int[] mData;
> 
>     int opIndex(size_t idx)
>     {
>         return mData[idx];
>     }
> }
> 
> int[] realArray = [1, 2, 3];
> realArray[0]++; // now contains [2, 2, 3]
> 
> IntArray a;
> a.mData = [1, 2, 3];
> a[0]++; // FAIL
> 
> In other words without these opIndexSomethingAssign overloads or ref returns 
> it's impossible to make a user container type behave just like a built-in 
> one.
> 
> (as an aside MiniD solves this by defining "a[0]++" to be "temp = a[0]; 
> temp++; a[0] = temp;" but that's beside the point.) 

So it sounds like what you actually meant was opIndexAddAssign.
opIndexConcatAssign would be like a[0]~=10.

But anyway, generally going that route would require creating a whole 
slew of new operators, basically an opIndex version of every current 
op***Assign operator.  That *would* give a class designer fine grained 
control over what was allowed and not allowed, but it's probably overkill.

On the other hand, the "return a reference" solution also has drawbacks 
in that it exposes the implementation and gives up control over the 
element.  Consider for instance an array wrapper where you want to track 
every modification to every element.  Currently you can do that quite 
easily by making opIndexAssign the only means of modifying the data. 
But then you can't do things like a[10] += 5.   So I think there's a 
place for the solution you use in MiniD as well.  Even after reference 
returns become possible I'd be happy to see the compiler use that trick 
in cases where there is no reference-returning version of opIndex defined.

--bb



More information about the Digitalmars-d mailing list