static array with inferred size

Steven Schveighoffer schveiguy at yahoo.com
Thu Sep 21 12:47:30 UTC 2017


On 9/20/17 1:33 PM, ag0aep6g wrote:
> 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]));
> }
> ----

I had no idea you could use static arrays for typesafe variadics! You 
learn something new every day :)

It's still a bit clunky. If you are explicitly specifying the type, you 
can't use an array literal, you must use the variadic form:

auto x1 = s("hello"); // x1 is char[5]
auto x2 = s!char("hello"); // T == char, but it fails?
auto x3 = s!char('h','e','l','l','o'); // works, but not pleasant.

I think when IFTI is given the type, it should still infer the size from 
the parameter.

This is close to a solution. I think if Jonathan's bug was fixed, we 
wouldn't even need the variadic form, though it could be useful as 
there's no way for the compiler to accidentally allocate on the heap. 
However, I still feel the compiler doing the work is a better choice. 
This is really basic initializer stuff, and generating templates for 
every call isn't always a good idea.

The slicing thing is ugly too... Doesn't that make an unnecessary copy?

-Steve


More information about the Digitalmars-d mailing list