Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different template behavior for integer and real types

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.

like image 371
vladon Avatar asked Sep 27 '26 19:09

vladon


1 Answers

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"; 
}
like image 112
TartanLlama Avatar answered Sep 29 '26 11:09

TartanLlama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!