c++ - 根据 value_type 调用适当的构造函数 : integer or float

标签 c++ templates c++11

我有一个函数,它使用均匀分布将最小值和最大值之间的随机值填充到容器中。

#include <iostream>
#include <random>
#include <algorithm>
#include <vector>

template<typename TContainer>
void uniform_random(TContainer& container, 
const typename TContainer::value_type min, 
const typename TContainer::value_type max) {
    std::random_device rd;
    std::mt19937 gen(rd());

    // Below line does not work with integers container
    std::uniform_real_distribution<typename TContainer::value_type> distribution(min, max);

    auto lambda_norm_dist = [&](){ return distribution(gen); };
    std::generate(container.begin(), container.end(), lambda_norm_dist);
}

int main() {
    std::vector<float> a(10);
    uniform_random(a,0,10);
    for (auto el : a) { std::cout << el << " "; }
}

替换 std::vector<float>std::vector<int>不起作用,因为我必须使用 std::uniform_int_distribution反而。 是否有一种简单而优雅的方法来根据 value_type 参数选择正确的构造函数?

到目前为止,我一直在尝试使用 std::numeric_limits<typename TContainer::value_type>::is_integer没有成功。

最佳答案

在 C++14(或稍作改动的 C++11)中,您可以通过这种方式创建一个 uniform_distribution 类型别名:

template <typename ValueType>
using uniform_distribution = std::conditional_t<
    std::is_floating_point<ValueType>::value,
    std::uniform_real_distribution<ValueType>,
    std::uniform_int_distribution<ValueType>
 >;

用法:

uniform_distribution<typename TContainer::value_type> distribution(min, max);

关于c++ - 根据 value_type 调用适当的构造函数 : integer or float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29747259/

相关文章:

c++ - 模版的歧义

c++ - 选择模板参数不同的模板类构造器导致编译失败

c++ - 使用 gcc 编译 .cpp

c++ - 范围内的模板变量或模板 typedef

c++ - 递归地包含头文件以进行合成

c++ - SSE2 内在函数 - 比较无符号整数

c++ - C++ 模板实现文件的正确文件扩展名是什么?

c++ - 如何在未使用 C++ 连接到 DC 时获取成员计算机的专有名称

c++ - 在 C++ 中传递回调函数参数的最佳方法

c++ - 没有删除运算符的 shared_ptr 内存泄漏