整数和实数类型的不同模板行为

vla*_*don 3 c++ templates c++11

如何为不同类型(某些伪语言)创建具有不同行为的模板,例如:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

怎么写那些if T is of xxx type

如果有意义,我使用C++ 11.

Tar*_*ama 5

使用if语句的问题在于T,无论是否实际运行代码,都需要对任何实体进行编译.

你最好使用专业化或类似的来指定你的行为.使用SFINAE和type_traits标题的示例:

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"; 
}
Run Code Online (Sandbox Code Playgroud)