On 01/11/2017 11:30 AM, Stefan Koch wrote:
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. It is very
similar with [1],
the difference being that it is uninitialized. Here is the code:
[...]
I believe you should not do this with recursion.
Because that'll instantiate the template multiple times with different
types.
What is wrong with using ndslice here ?
Agreed but the question is still valid. I had similar cases before where
std.range.choose looked like a solution but did not work. Here's my
current attempt, which fails:
import std.stdio;
import std.experimental.allocator.gc_allocator;
import std.experimental.allocator;
auto one(T, Allocator)(auto ref Allocator alloc, size_t length) {
return makeArray!T(alloc, length);
}
auto two(T, Allocator)(auto ref Allocator alloc, size_t[] lengths) {
// Error: forward reference to inferred return type of function call
'makeMultidimensionalArray!int(alloc, lengths[1..__dollar])'
alias E = typeof(makeMultidimensionalArray!T(alloc, lengths[1..$]));
auto ret = makeArray!E(alloc, lengths[0]);
foreach (ref e; ret)
e = makeMultidimensionalArray!T(alloc, lengths[1..$]);
return ret;
}
auto makeMultidimensionalArray(T, Allocator)(auto ref Allocator alloc,
size_t[] lengths)
{
import std.range: choose;
return choose(lengths.length == 1, one!T(alloc, lengths[0]),
two!T(alloc, lengths));
}
void main() {
writeln(makeMultidimensionalArray!int(GCAllocator.instance, [3, 4]));
}
Ali