我打算写一个模板来生成随机数据的向量.问题是
std :: uniform_int_distribution只接受整数类型,而float类型的std :: uniform_real_distribution.我想把两者结合起来.这是我的代码.
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; }