简体   繁体   中英

C++14 Template enable_if return type

I have the following code witch takes an 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 wich 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.

You can use

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

to make the type defined be T rather than void .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM