inferred size for static array initialization
Basile B via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 2 06:46:25 PDT 2016
On Monday, 2 May 2016 at 13:22:01 UTC, Basile B wrote:
> 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 ?
Using an enum is probably a bit better
----
auto toStaticArray(alias array)()
if (isDynamicArray!(typeof(array)) && array.length)
{
alias T = typeof(array[0])[array.length];
enum T result = array[0..array.length];
return result;
}
More information about the Digitalmars-d-learn
mailing list