Passing Arguments on in Variadic Functions
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Sep 14 13:12:16 PDT 2015
On Monday, 14 September 2015 at 19:59:18 UTC, jmh530 wrote:
> In R, it is easy to have some optional inputs labeled as ...
> and then pass all those optional inputs in to another function.
> I was trying to get something similar to work in a templated D
> function, but I couldn't quite get the same behavior. What I
> have below is what I was able to get working.
You want to generally avoid the varargs and instead use variadic
templates. The syntax is similar but a bit different:
R test(R, E, Args...)(Args args) {
static if(Args.length == 0)
// no additional arguments
else
return sum(args);
}
or whatever you actually need. But what this does is take any
number of arguments of various types but makes that length and
type available at compile time for static if inspection.
The args represents the whole list and you can loop over it,
convert to an array with `[args]` (if they are all compatible
types, or pass to another function as a group like I did here.
This is the way writeln is implemented btw.
More information about the Digitalmars-d-learn
mailing list