More magical AA semantics

Timon Gehr timon.gehr at gmx.ch
Fri Jan 11 16:26:20 PST 2013


On 01/11/2013 08:53 AM, Don wrote:
> Consider this code:
> ---
>     int[int] x;
>
>     int k = x[2] + 5; // Error, range violation. Makes sense.
>
>     x[2] = x[2] + 5;  // But this works!!!
> ---
>
> That is, x[2] doesn't exist, *unless you are about to assign to
> it*.
>
> What happens is:
> 1. lvalue index (creates x[2], sets it to int.init)
> 2. rvalue index (returns x[2], which is now 0)
> 3. lvalue index assign (sets x[2] = 5)
>
> In reality, step 1 returns a pointer to the newly created element.
>
> How could this be implemented as a library type?
> The superficially similar case, x[2] += 5; can be implemented
> with opIndexOpAssign. But I don't know how to do this one.
>

struct S{
	private int[int] x;
	int opIndex(int k){
		return x[k];
	}
	void opIndexAssign(lazy int v, int k){
		x[k]=v;
	}
}

void main(){
	S x;
	int k = x[2] + 5; // Error
	x[2] = x[2] + 5;  // Ok
}

=P

> Note that elements are not always magically created when an
> lvalue is required. AFAIK it only happens in assignment. For
> example this code gives a runtime error:
> ---
> void foo(ref int g) { ++g; }
>
>     int[int] x;
>     foo( x[2] );  // range error, x[2] doesn't exist yet
> ---

Now I'm lost too. Anyway, I do not consider the behaviour particularly 
useful.




More information about the Digitalmars-d mailing list