Are templates with variadic value parameters possible?

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 15 08:56:00 PDT 2016


On Friday, 15 July 2016 at 15:04:22 UTC, Devin Hill wrote:

>
> to the condition. It works pretty well! Granted, it doesn't 
> allow for calling it in two ways like a variadic version would 
> have:
>
> foo(1, 2, 3)   // works with this setup
> foo([1, 2, 3]) // doesn't, but would only be occasionally 
> useful anyway
>
> but all in all it's a decent workaround for the problem.

It isn't too much effort to add support for both:

```
import std.traits : isArray, ForeachType;
import std.stdio : writeln;

void func(Args...)(Args args)
     if(is(Args[0] : long) || (isArray!(Args[0]) && 
is(ForeachType!(Args[0]) : long)))
{
     static if(isArray!(Args[0])) {
         foreach(i; args[0])
             writeln(i);
     }
     else {
         foreach(arg; args)
             writeln(arg);
     }
}

void main()
{
     func(10, 20, 30, 40);
     func([1, 2, 3, 4, 5]);
}
```

Or, alternatively, to support multiple arrays:

```
void func(Args...)(Args args)
     if(is(Args[0] : long) || (isArray!(Args[0]) && 
is(ForeachType!(Args[0]) : long)))
{
     foreach(arg; args) {
         static if(isArray!(Args[0])) {
             foreach(i; arg) writeln(i);
         }
         else writeln(arg);
     }
}

void main()
{
     func(10, 20, 30, 40);
     func([1, 2, 3, 4, 5], [100, 200, 300, 400]);
}
```


More information about the Digitalmars-d-learn mailing list