Hello bearophile,

Philippe Sigaud:

Would a template-based solution be OK?

import std.stdio, std.traits;

CommonType!T[T.length] staticArray(T...)(T vals)
if ((T.length > 0) && is(CommonType!T))
{
return [vals];
}
That's one solution, but code like that is most useful when your
arrays liters are long (because if they are little you can just count
the items and avoid using staticArray), this is an example (I have
used printf to avoid the metric ton of functions and templates used by
writeln):

import std.c.stdio: printf;
import std.traits: CommonType;
CommonType!T[T.length] staticArray(T...)(T vals)
if (T.length && is(CommonType!T)) {
return [vals];
}
void main() {
auto a = staticArray(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
...
990);
printf("%d\n", a[2]);
}
This is the asm of the staticArray:

_D5test2217__T11staticArrayTiÉÛÿ€€  €ÀÀ€ÈÈZÖFiiÉÛÿ€€  €¤¤ZG100i
comdat
L0:     push    EAX
push    ESI
push    EDI
push    dword ptr 010h[ESP]
...
push    dword ptr 0328h[ESP]
push    064h
push    ECX
call    near ptr __d_arrayliteralT
mov ESI,EAX
mov EDI,01A0h[ESP]
mov ECX,064h
rep
movsd
add ESP,0198h
mov EAX,8[ESP]
pop EDI
pop ESI
pop ECX
ret 0190h

Is that with or without inline? If that doesn't inline away to a memcopy then it looks like an optimization opportunity to me.

And you essentially have one similar function each time you use
staticArray. This is why in my answer I have said I don't know any
good solution to this problem and this is why I have proposed the
enhancement [$] syntax.

In my code I count the items in some way (with Python, or I assign the
literal to a dynamic array, print its length and then modify the code
replacing the dynamic array with the printed number).

Bye,
bearophile
--
... <IXOYE><



Reply via email to