How to properly use variadic templates (functions)?

Anonymouse zorael at gmail.com
Tue Dec 21 08:11:39 UTC 2021


On Tuesday, 21 December 2021 at 06:44:36 UTC, rempas wrote:
> This will not do for me because I want to do formatted output 
> and I need the index. But thanks a lot for tying to help!

I'm not certain I understand, but won't `foreach (i, a; args) { 
/* ... */ }` in his example do that?

As in, if you necessarily must index `args` instead of using a 
foreach variable,

```d
import core.stdc.stdio : putc, stdout;

void print(T...)(string prompt, T args)
{
     foreach (i, a; args)
     {
         alias A = typeof(args[i]);

         static if (is(A : string))
         {
             for (int j = 0; j < args[i].length; j++)
             {
                 putc(args[i][j], stdout);
             }
         }
         else
         {
             // handle your other types
             print("", A.stringof);
         }
     }
}

void main()
{
     print("Prompt (ignored)", "Hello", " world!\n", 123);
}
```


More information about the Digitalmars-d-learn mailing list