如何使用condition检查typename T是否为C中的float类型的整数类型

我打算写一个模板来生成随机数据的向量.问题是
std :: uniform_int_distribution只接受整数类型,而float类型的std :: uniform_real_distribution.我想把两者结合起来.这是我的代码.
#include <vector>
#include <random>
#include <algorithm>
#include <iterator>
#include <functional>

template<typename T>
std::vector<T> generate_vector(size_t N,T lower = T(0),T higher = T(99)) {
    // Specify the engine and distribution. 
    if constexpr (std::is_integral<T>) {
    std::uniform_int_distribution<T> distribution(lower,higher);
    }
    else if constexpr (std::is_floating_point<T>) {
    std::uniform_real_distribution<T> distribution(lower,higher);
    }
    std::mt19937 engine; // Mersenne twister MT19937
    auto generator = std::bind(distribution,engine);
    std::vector<T> vec(N);
    std::generate(vec.begin(),vec.end(),generator);
    return vec;

我很困惑如何在if条件下实现语句.整数类型应包括:short,int,long,long long,unsigned short,unsigned int,unsigned long或unsigned long long.浮点类型包括float,double或long double.

任何帮助建议?

解决方法

在C17之前的编译器中,您可以使用模板特化来实现if-else逻辑.
// Declare a class template
template <bool is_integral,typename T> struct uniform_distribution_selector;

// Specialize for true
template <typename T> struct uniform_distribution_selector<true,T>
{
   using type = typename std::uniform_int_distribution<T>;
};

// Specialize for false
template <typename T> struct uniform_distribution_selector<false,T>
{
   using type = typename std::uniform_real_distribution<T>;
};


template<typename T>
std::vector<T> generate_vector(size_t N,T higher = T(99))
{
   // Select the appropriate distribution type.
   using uniform_distribution_type = typename uniform_distribution_selector<std::is_integral<T>::value,T>::type;

   uniform_distribution_type distribution(lower,higher);
   std::mt19937 engine;
   auto generator = std::bind(distribution,engine);
   std::vector<T> vec(N);
   std::generate(vec.begin(),generator);
   return vec;
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...