More on C++ stack arrays

Nick Treleaven ntrel-public at yahoo.co.uk
Tue Oct 22 04:34:08 PDT 2013


On 20/10/2013 21:39, Tove wrote:
>
> ref E stalloc(E)(ref E mem = *(cast(E*)alloca(E.sizeof)))
> {
>    return mem;
> }

Another trick is to use a template alias parameter for array length:

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

void main(string[] args)
{
     auto n = args.length;
     int[] arr = stackArray!(int, n)();
}

Note: The built-in length property couldn't be aliased when I tested 
this, hence 'n'. Reference:

http://forum.dlang.org/post/aepqtotvkjyausrlsmad@forum.dlang.org


More information about the Digitalmars-d mailing list