Is this proper use of std::enable_if? It works, but is it correct?
//*.h file
template <typename T>
static typename std::enable_if<std::is_integral<T>::value, T>::type
randomFrom(const T min, const T max);
template <typename T>
static typename std::enable_if<std::is_floating_point<T>::value, T>::type
randomFrom(const T min, const T max);
.
//*.inl file
template <typename T>
inline typename std::enable_if<std::is_integral<T>::value, T>::type
Math::randomFrom(const T min, const T max)
{
static std::default_random_engine re((unsigned long)time(0));
std::uniform_int_distribution<T> uni(min, max);
return static_cast<T>(uni(re));
}
template <typename T>
inline typename std::enable_if<std::is_floating_point<T>::value, T>::type
Math::randomFrom(const T min, const T max)
{
static std::default_random_engine re((unsigned long)time(0));
std::uniform_real_distribution<T> uni(min, max);
return static_cast<T>(uni(re));
}
How can I rewrite it, to achieve cleaner interface? Like:
template <typename T>
static T randomFrom(const T min, const T max);
BTW with boost I had something like: (i do not want to use boost)
typedef typename boost::mpl::if_<
boost::is_floating_point<T>,
boost::uniform_real<>,
boost::uniform_int<>>::type dist_type;
and whole behavior was solved in single function. But there is nothing like std::if
right?
Your usage is fine, and very much idiomatic.
The equivalent to Boost.MPL's if_
would be std::conditional
:
typedef typename std::conditional<
std::is_floating_point<T>::value,
std::uniform_real_distribution<T>,
std::uniform_int_distribution<T>>::type dist_type;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With