Search code examples
c++templatesc++14sfinae

C++14 Template enable_if return type


I have the following code which takes a value and returns a random value between 0 and that value:

template<typename T>
typename std::enable_if<!std::is_integral<T>::value>::type
RandomGenerator::random(T value) {
    std::uniform_real_distribution<T> dist(0, value);
    return dist(RandomGenerator::mt);
}

my problem here is that the return type is void and I wanted it to be T.

the enable_if is there to avoid another function similar to this one but uses the std::uniform_int_distribution for integral types which also has the same problem.

How can I write a function that can run the following example code:

auto BaseAngle = 10.0f;
//add a bit of randomness to the angle
BaseAngle += RandomGenerator::random(45.0f);

Thanks in advance.


Solution

  • You can use

    std::enable_if<!std::is_integral<T>::value, T>
    

    to make the type defined be T rather than void.