Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of std::enable_if or how to replace it

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?

like image 606
relaxxx Avatar asked Dec 06 '22 12:12

relaxxx


1 Answers

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;
like image 67
Luc Danton Avatar answered Dec 09 '22 15:12

Luc Danton