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.

Reply via email to