to! converting 1D to 2D array

monarch_dodra monarchdodra at gmail.com
Tue Mar 11 23:53:18 PDT 2014


On Wednesday, 12 March 2014 at 03:37:49 UTC, ed wrote:
> Thanks for explaining this, it makes sense what you said. But 
> I'm still not sure why my original Example 1 worked.
>
> ~~~
> // This works OK and converts long[4] to int[] then implicitly 
> to int[2][2]
> long[4] a=[1,2,3,4];
> int[2][2] b = to!(int[])(a);
>
> // Why does this not work the same way?
> long[4] a=[1,2,3,4];
> int[2][2] b;
> b = to!(int[])(a);
> ~~~
>
> My understanding of your explanation is that it shouldn't work.
>
>
> Cheers,
> ed

I *believe* it's really just that you are allowed to *initialize* 
a static array (of any depth) from a dynamic array.

However, for assignment, it doesn't work that way:

     int[] a = [0, 1, 2, 3];
     int[2][1][2][1] b = a; //OK!
     b = a; //ERROR

If you want do want to do the assignment, you'll have to 
re-interpret your array's layout:

     int[] a = [0, 1, 2, 3];
     int[2][1][2][1] b;
     *cast(int[4]*)&b = a;
     assert(b == [[[[0, 1]], [[2, 3]]]]);


More information about the Digitalmars-d-learn mailing list