根据value_type调用适当的构造函数:integer或float [英] Call appropriate constructor depending on value_type : integer or float
问题描述
我有一个函数使用均匀分布在最小和最大值之间填充随机值。
I have a function which fills a container with random values between min and max using uniform distribution.
#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& / code>与
std :: vector< int>
不工作,因为我必须使用 std :: uniform_int_distribution
。
根据value_type参数,有一个简单而优雅的方法来选择正确的构造函数?
Replacing std::vector<float>
with std::vector<int>
does not work since I would have to use std::uniform_int_distribution
instead.
Is there a simple and elegant way to pick the right constructor depending on the value_type parameter ?
我试图使用 std :: numeric_limits< typename TContainer :: value_type> :: is_integer
未成功。
推荐答案
一个元函数 select_distribution
,它允许您写下:
Write a meta-function select_distribution
which allows you to write this:
using value_type = typename TContainer::value_type;
using distribution_type = typename select_distribution<value_type>::type;
distribution_type distribution(min, max);
其中 select_distribution
定义为: p>
where select_distribution
is defined as:
template<typename T, bool = std::is_floating_point<T>::value>
struct select_distribution
{
using type = std::uniform_real_distribution<T>;
};
template<typename T>
struct select_distribution<T, false>
{
using type = std::uniform_int_distribution<T>;
};
希望有帮助。
这篇关于根据value_type调用适当的构造函数:integer或float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!