static arrays at runtime with templates ?

XavierAP n3minis-git at yahoo.es
Mon Feb 4 22:48:10 UTC 2019


On Monday, 4 February 2019 at 19:14:38 UTC, Emil wrote:
>
> Can std.array.staticArray build static arrays with size known 
> only at run time ? Now that I am not overcome with enthousiasm 
> it looks like it too needs to know the size.

A static array's size must be known (or computed) at compile 
time, by definition... There can be no exception; staticArray() 
gets or infers the size from its template/compile-time arguments.

For one, the trivial example on dlang.org/phobos
     auto a = [0, 1].staticArray;
     static assert(is(typeof(a) == int[2]));
is equivalent to
     int[2] a = [0, 1];
     static assert(is(typeof(a) == int[2]));
Is it better? Depends on.....? No it really isn't...

However one of the possibilities of D is the ability to generate 
and execute quite some code at compile time by means of 
meta-programming; and I guess here's where staticArray() may end 
up being useful enough to have merited introduction into the std 
library; not for trivial uses where a straightforward T[n] 
declaration is preferable, being possible...

If there is something you want to solve in a program of yours, 
there may be another way, as H.S. Teoh suggests. If you're just 
trying out stuff it's also fine, :) there's still more.


More information about the Digitalmars-d-learn mailing list