inferred size for static array initialization
Basile B via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 2 06:22:01 PDT 2016
On Monday, 2 May 2016 at 13:00:27 UTC, Erik Smith wrote:
> Is there a way to initialize a static array and have it's size
> inferred (and that works for arrays of structs using braced
> literals)? This would make it easier to maintain longer static
> array definitions. The code below doesn't work when removing
> the array size even though the array is declared as static
> immutable.
>
> import std.traits;
> static immutable int[] a = [1,2,3];
> static assert(isStaticArray!(typeof(a))); // fails
Help yourself with a template:
----
import std.traits;
auto toStaticArray(alias array)()
if (isArray!(typeof(array)))
{
enum size = array.length;
alias T = typeof(array.init[0])[size];
T result = array[0..size];
return result;
}
enum a = toStaticArray!([1,2,3]);
static assert(isStaticArray!(typeof(a))); // success
----
Does it fit ?
More information about the Digitalmars-d-learn
mailing list