I would like to use C++11’s variadic templates to achieve a generalized “random picker” function.
Something like this…
template <typename T>
T randomPicker(T one, T two, T three)
{
int pick = 3 * (rand() / double(RAND_MAX));
switch (pick)
{
case 0:
return one;
case 1:
return two;
default:
return three;
}
}
… except generalized to accept any number of parameters (each of the same type, as above — although accepting any type as a parameter and converting the chosen one to some specific type T upon return would be acceptable also).
I understand the idea of using template recursion to achieve things like the typesafe printf, etc. Can variadic templates also be used to create the sort of function described above? Any tips appreciated!
Something like this, although I can’t test it:
I’m not sure whether the overload there is right — presumably a parameter pack can be empty, I don’t know whether I can still overload for one argument without ambiguity.
Admittedly this uses more random numbers than your example with 3 args, and may be more sensitive to bias from rounding errors. So, you could pick a random number from
0tolen-1at the start, and then call a recursive function that selects thenth argument out of the parameter pack:In all cases, I have
nif/else statements instead of ann-way switch. You might be lucky with the optimizer, or you might be able to “unroll the loop” a bit by havingFirst,Second…A fewparameter args before the variable args.