How to create template with different behavior for different types (some pseudo language), for example:
template <typename T>
T GetRand(T param)
{
if (T is of any real type) {
// use uniform_real_distribution
}
if (T is of any integer type) {
// use uniform_int_distribution
}
if (T is of any other type) {
// do nothing
}
}
How to write those if T is of xxx type?
If it makes sense, I use C++11.
The problem with using if statements like that is that the bodies need to be compilable for any T, regardless of whether that code would ever actually be run.
You would be better off using specialization or similar to specify your behaviour. An example which uses SFINAE and the type_traits header:
template <typename T, std::enable_if_t<std::is_integral<T>::value>* = nullptr>
T GetRand(T param)
{
cout << "int version\n";
}
template <typename T, std::enable_if_t<std::is_floating_point<T>::value>* = nullptr>
T GetRand(T param)
{
cout << "float version\n";
}
template <typename T,
std::enable_if_t<!(std::is_floating_point<T>::value ||
std::is_integral<T>::value)>* = nullptr>
T GetRand(T param)
{
cout << "other version\n";
}
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