static array with inferred size

ag0aep6g anonymous at example.com
Wed Sep 20 17:33:49 UTC 2017


On 09/20/2017 06:55 PM, Steven Schveighoffer wrote:
> On 9/20/17 11:48 AM, Dgame wrote:
[...]
>> ----
>> Unqual!T[n] s(T, size_t n)(T[n] arr)
>> {
>>      return arr;
>> }
>>
>> auto a = "hallo".s;
>> writeln(typeof(a).stringof); // char[5]
>> ----
[...]
> Still it can't handle the case of:
> 
> ubyte[3] x = [1, 2, 3];

Making the parameter variadic seems to do the trick:

----
import std.traits: Unqual;

Unqual!T[n] s(T, size_t n)(T[n] arr ...)
{
      return arr[];
         /* With indirections, dmd would complain about an
         escaping reference. Slicing shuts it up. */
}

void main()
{
     auto a = s("hello");
     static assert(is(typeof(a) == char[5]));

     auto x = s!ubyte(1, 2, 3);
     static assert(is(typeof(x) == ubyte[3]));

     auto y = s(new int, new int);
     static assert(is(typeof(y) == int*[2]));

     auto z = s(new immutable int, new immutable int);
     static assert(is(typeof(z) == immutable(int)*[2]));
}
----


More information about the Digitalmars-d mailing list