Multi dimensional array question.

Heywood Floyd soul8o8 at gmail.com
Fri Jul 16 02:12:27 PDT 2010


Lars T. Kyllingstad Wrote:
 
> I do agree that, if possible, the language should match how most people 
> think.  But in this case, it is impossible, because of templates.  How 
> would the following example work with T = int[3], if arrays worked the 
> way you want?
> 
>   struct MyArray(T)
>   {
>       T[] a;
>   }
> 
> C doesn't have this issue, because it doesn't have templates.  And I'll 
> have my templates over C-style array declarations any time, thank you. :)
> 
> -Lars


Well, I suppose the obvious way is to introduce array as a proper type, and not
just as syntactical sugar. For instance, consider:

array[11] int myArr; 

The array "wraps around" a more basic type. It's simply read from left to right.
This should feel "right" for most people. Now it's easy extend this to 
multidimensional arrays. We just allow arrays to wrap arrays:

array[3] array[11] int myArr2d;

This way it's clear what's happening. It's "true" to what's going on at the
compiler level. We have an "outer" array that holds 3 "inner" arrays of 11 ints. 
And, it's "true" to our high level semantics—when we later access the elements, 
the order is kept intact, as we traverse down the array stack:

myArr2d[outer][inner] = 9;

It's then not too far of a stretch to allow this array-keyword to accept
multidimensional declarations, without reversing the order. Here, it's
still quite clear what's happening: (At least if we have seen the above.)

array[3][11] int myArr2d;
myArr2d[0][10] = 9; //ok

When we introduce templates, this should still work:

struct MyArray(T){
   array[3] T a;
}

// Let's try
T == array[11] int

array[3] T a;
array[3] (array[11] int) a;
array[3] array[11] a;
array[3][11] a;

a[0][10] = 9; //ok

This makes a lot more sense, for me anyway. It's closer to what's actually happening,
and it doesn't reverse things at a higher level.

BR
/HF




More information about the Digitalmars-d-learn mailing list