小编Alp*_*ius的帖子

如何使用“if constexpr”正确实现“operator()”,以便它与 std::generate 一起使用?

我试图编写一个类,该类将用容器具有的类型的随机数填充容器:

template<typename random_type>
class rand_helper {
private:
    std::mt19937 random_engine;
    std::uniform_int_distribution<int> int_dist;
    std::uniform_real_distribution<double> real_dist;

public:
    rand_helper() = delete;
    rand_helper(random_type left_b, random_type right_b);
    random_type operator()();

};

template<typename random_type>
rand_helper<random_type>::rand_helper(const random_type left_b, const random_type right_b) :random_engine{ std::random_device{}()} {
    if constexpr (std::is_same_v<random_type, double>)
        real_dist(left_b, right_b );
    else
        int_dist( left_b, right_b );
}

template<typename random_type>
random_type rand_helper<random_type>::operator()() {
    if constexpr (std::is_same_v<random_type, double>)
        return real_dist(random_engine);
    else
        return int_dist(random_engine);
}

Run Code Online (Sandbox Code Playgroud)

但是这里某处发生错误,因为当我调用 std::generate 时,我会收到很多错误:

template<typename T,typename vec_type = typename T::value_type>
void fill_contain(T& container,vec_type left_b=vec_type(0), vec_type right_b= vec_type(100)) { …
Run Code Online (Sandbox Code Playgroud)

c++ random template-instantiation

3
推荐指数
1
解决办法
90
查看次数

标签 统计

c++ ×1

random ×1

template-instantiation ×1