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.
This approach gives the correct result, but dmd won't deduce the
type of the template. So for instance, the second to the last
line of the unit test requires explicitly stating the types. I
may as well use the alternate version that doesn't use the
variadic function (which is simple for this trivial example, but
maybe not more generally).
Do I have any options to get it more similar to the way R does
things?
import std.algorithm : sum;
import core.vararg;
auto test(R)(R r)
{
return sum(r);
}
auto test(R, E)(R r, ...)
{
if (_arguments.length == 0)
return test(r);
else
{
auto seed = va_arg!(E)(_argptr);
return sum(r, seed);
}
}
auto test_alt(R, E)(R r, E seed)
{
return sum(r, seed);
}
unittest
{
int[] x = [10, 5, 15, 20, 30];
assert(test(x) == 80);
assert(test!(int[], float)(x, 0f) == 80f);
assert(test_alt(x, 0f) == 80f);
}