Discussion Thread: DIP 1039--Static Arrays with Inferred Length--Community Review Round 1

Luhrel lucien.perregaux at gmail.com
Wed Jan 6 19:27:20 UTC 2021


On Wednesday, 6 January 2021 at 19:04:14 UTC, jmh530 wrote:
> On Wednesday, 6 January 2021 at 18:34:31 UTC, Nick Treleaven 
> wrote:
>> [...]
>
> What about something like below to handle any user-defined type.
>
> import std.stdio: writeln;
>
> template staticArray(T) {
>     T[n] staticArray(ulong n) (auto ref T[n] a) {return a;}
>
>     T[n] staticArray(U, ulong n) (auto ref U[n] a)
>         if (!is(T == U))
>     {
>         T[n] output;
>         for(size_t i = 0; i < n; i++) {
>             output[i] = cast(T) a[i];
>         }
>         return output;
>     }
> }
>
> T[n] staticArray(T, ulong n) (auto ref T[n] a) {return a;}
>
> struct Foo {
>     float x;
>     T opCast(T)() {
>         return cast(T) x;
>     }
> }
>
> void main(){
>     auto a = [1,2,3].staticArray!float;
>     pragma(msg, typeof(a)); // float[3]
>     a.writeln();
>     [1,2,3].staticArray.writeln();
>
>     auto b = [1,2,3].staticArray!Foo;
>     b.writeln();
> }

This works fine, even in betterC mode with LDC.
Doesn't work with betterC with DMD 
(https://issues.dlang.org/show_bug.cgi?id=19946).

I still don't like the .staticArray, but I'll use it if this DIP 
isn't approved.

Maybe `[$]` can be a shortcut to .staticArray.



More information about the Digitalmars-d-announce mailing list