On Tuesday, 5 February 2013 at 20:47:46 UTC, Nick Treleaven wrote:
On 05/02/2013 16:47, monarch_dodra wrote:
On Tuesday, 5 February 2013 at 16:37:41 UTC, Nick Treleaven wrote:
I've just realized this doesn't work for variable-length allocation:

T[] stack(T)(size_t N, void* m = alloca(T.sizeof * N))

Error: undefined identifier N, did you mean alias T?

N is not visible in the caller's scope.

It does, just alias it.

//----
import std.stdio;
import core.stdc.stdlib:alloca;

T* stack(T)(void* m = alloca(T.sizeof))
{
    return cast(T*)m;
}
T[] stack(T, alias N)(void* m = alloca(T.sizeof * N))
{
    return (cast(T*)m)[0 .. N];
}

This works if you know N at compile-time. But there doesn't seem to be a way to wrap alloca to accept a runtime-only value, e.g.:

// allocate as many ints as command-line parameters
int[] arr = stack!int(args.length);

I don't have access to my compiler, but that *should*work. Did you try it? BTW, the syntax would be:

int[] arr = stack!(int, args.length)();

Reply via email to