On Wednesday, 11 January 2017 at 19:23:10 UTC, Razvan Nitu wrote:
Hi,

I am currently trying to create a function makeMultidimensionalArray which allocates memory for a multidimensional array.

You were very close to the answer:

auto makeMultidimensionalArray(int N, T, Allocator)(auto ref Allocator alloc, size_t[N] lengths)
{
    static if (lengths.length == 1)
    {
        return makeArray!T(alloc, lengths[0]);
    }
    else
    {
alias E = typeof(makeMultidimensionalArray!(N-1,T)(alloc, lengths[1..$]));
        auto ret = makeArray!E(alloc, lengths[0]);
        foreach (ref e; ret)
e = makeMultidimensionalArray!(N-1, T)(alloc, lengths[1..$]);
        return ret;
    }
}


The key point is that return type depends on length of "lengths" array (dimensionality), so if this length is only known at runtime this is a dependent type, something D lacks (you'll need Idris or Agda for those). In D return type must be known at compile time and hence the length of "lengths" must be a compile time argument. With such argument everything compiles smoothly.

Reply via email to