Array to argument list

Sergey Gromov snake.scaly at gmail.com
Thu Sep 11 10:07:13 PDT 2008


Simen Haugen <simen at norstat.no> wrote:
> I have an array, but I want to send them one by one to a function that 
> has variadic arguments. Is there a way to do this at runtime?
> 
> void p(A ...)(A Args) {}
> p([1, 2, 3]); // I want this to become p(1, 2, 3) somehow...

With a bit of template trickery I've got this:

> import std.stdio;
> 
> void p(A ...)(A Args) {
>   writeln(A.stringof);
>   writeln(Args[4]);
> }
> 
> void PassArrayAsTuple(alias fun, T: E[S], E, size_t S, R...)(T arr, R rest) {
>   static if (S)
>     PassArrayAsTuple!(fun)(cast(E[S-1])arr, arr[$-1], rest);
>   else
>     fun(rest);
> }
> 
> void main() {
>   PassArrayAsTuple!(p)("array");
> }

Obviously it works only for static arrays.
I wanted to come up with something like

p(ArrayTuple!("array"));

but the trick with casting a static array to a smaller static array does 
not work for template arguments.  I'm not sure that it should work for 
function arguments either, bit it works in DMD 2.019 indeed.


More information about the Digitalmars-d-learn mailing list