On Monday, 14 September 2015 at 20:26:56 UTC, jmh530 wrote:
Thanks to you both. This works perfect.

I noticed that there's some interesting interplay with this technique and default arguments.

From below, it is required that you put the ones with default arguments last. If there are only two arguments, then it takes the second to be the default argument. However, I can't actually put just one argument, even though V is variadic and sample is a default. That seems strange to me because it makes it seem like sample really isn't optional.

Not sure if this is a bug or on purpose. The only way I can resolve it is by writing another function that just takes x (alternately one that takes x and sample only also works).

Also, it doesn't seem to let me put template constraints on V so that I could do something like constrain V to be numeric.

import std.algorithm : sum;
import std.stdio : writeln;

auto test(T, V ...)(T x, V seed, bool sample=true)
{
        auto sum_x = sum(x, seed);
        if (sample)
                return sum_x;
        else
                return sum_x / 2;
}

void main()
{
        int[] x = [10, 5, 15, 20, 30];
        writeln(test(x, true));
        writeln(test(x, false));
        float seed = 1;
        writeln(test(x, seed, true));
        writeln(test(x, seed, false));
}

Reply via email to