inferred size for static array initialization
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 2 11:15:00 PDT 2016
On 5/2/16 1:43 PM, Namespace 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
>
> I still like
> ----
> auto s(T, size_t n)(T[n] arr) {
> return arr;
> }
Interesting. But there is a major problem here...
>
> auto arr = [1, 2, 3].s;
> ----
>
> But of course this won't work:
> ----
> int[] a = [1,2,3].s;
> static assert(isStaticArray!(typeof(a))); // fails
> ----
And this is the problem.
> Since 'a' is just a slice.
A slice of a no-longer-existing temporary! Admittedly, this is not an
issue with your code, but a deeper issue of allowing slicing of rvalues.
>
> But this will work:
> ----
> immutable auto a = [1,2,3].s;
> ----
You can drop auto. It's just a placeholder for the storage class in the
case where a storage class isn't specified.
-Steve
More information about the Digitalmars-d-learn
mailing list