Monday, 19 August 2013

specializing a template on bool + integral + floating-point return types

specializing a template on bool + integral + floating-point return types

I'd like to write a function template which returns a random variable of
various types (bool, char, short, int, float, double, along with unsigned
versions of these).
I couldn't see how to do this using the latest C++11 standard library,
since I need to use either uniform_int_distribution or
uniform_real_distribution. I thought I could specialize the template:
template<typename T>
T randomPrimitive() { std::uniform_int_distribution<T> dst; std::mt19937
rng; return dst(rng); }
template<>
bool randomPrimitive() { std::uniform_int_distribution<char> dst;
std::mt19937 rng; return dst(rng) >= 0 ? true : false; }
template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type
randomPrimitive() { std::uniform_real_distribution<T> dst; std::mt19937
rng; return dst(rng); }
Under Visual Studio 2012 Update 3, this gives:
error C2668: '`anonymous-namespace'::randomPrimitive' : ambiguous call to
overloaded function
Is there a way to specialize a function template so I can write three
different implementations for bool, other integral types, and
floating-point types?

No comments:

Post a Comment