Dimensions in compile time

Rumbu rumbu at rumbu.ro
Mon Feb 8 13:09:53 UTC 2021


On Monday, 8 February 2021 at 12:19:26 UTC, Basile B. wrote:
> On Monday, 8 February 2021 at 11:42:45 UTC, Vindex wrote:
>> size_t ndim(A)(A arr) {
>>     return std.algorithm.count(typeid(A).to!string, '[');
>> }
>>
>> Is there a way to find out the number of dimensions in an 
>> array at compile time?
>
> yeah.
>
> ---
> template dimensionCount(T)
> {
>     static if (isArray!T)
>     {
>         static if (isMultiDimensionalArray!T)
>         {
>             alias DT = typeof(T.init[0]);
>             enum dimensionCount = dimensionCount!DT + 1;
>         }
>         else enum dimensionCount = 1;
>     }
>     else enum dimensionCount = 0;
> }
> ///
> unittest
> {
>     static assert(dimensionCount!char == 0);
>     static assert(dimensionCount!(string[]) == 1);
>     static assert(dimensionCount!(int[]) == 1);
>     static assert(dimensionCount!(int[][]) == 2);
>     static assert(dimensionCount!(int[][][]) == 3);
> }
> ---
>
> that can be rewritten using some phobos traits too I think, but 
> this piece of code is very old now, more like learner template.

dimensionCount!string should be 2.

My take without std.traits:

template rank(T: U[], U)
{
    enum rank = 1 + rank!U;
}

template rank(T: U[n], size_t n)
{
     enum rank = 1 + rank!U;
}

template rank(T)
{
     enum rank = 0;
}




More information about the Digitalmars-d-learn mailing list