Dimensions in compile time

Basile B. b2.temp at gmx.com
Mon Feb 8 13:44:51 UTC 2021


On Monday, 8 February 2021 at 13:27:14 UTC, Vindex wrote:
> Thanks everyone!
>
> The solution that works for me now looks like this:
>
>
> template ndim(T) {
>     static if (std.traits.isArray!T) {
>         static if (is(typeof(T.init[0]))) {
>             alias SubArrayType = typeof(T.init[0]);
>             enum ndim = ndim!SubArrayType + 1;
>         }
>         else enum ndim = 1;
>     }
>     else enum ndim = 0;
> }
> unittest {
>     assert(ndim!(int[]) == 1);
>     assert(ndim!(int[][]) == 2);
>     assert(ndim!(int[4][3]) == 2);
>     assert(ndim!(int[][2][]) == 3);
>     assert(ndim!(string) == 1);
> }

Nice. You should look at Rumbu solution too. It possibly has a 
better behavior toward the recursive expansion. Also interesting 
to learn the more advanced use of "is".


More information about the Digitalmars-d-learn mailing list