coi*_*oin 5 c++ templates c++11
我有一个函数,使用均匀分布填充具有min和max之间随机值的容器.
#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 << " "; }
}
Run Code Online (Sandbox Code Playgroud)
更换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>
>;
Run Code Online (Sandbox Code Playgroud)
用法:
uniform_distribution<typename TContainer::value_type> distribution(min, max);
Run Code Online (Sandbox Code Playgroud)
写一个元函数select_distribution,它允许你写这个:
using value_type = typename TContainer::value_type;
using distribution_type = typename select_distribution<value_type>::type;
distribution_type distribution(min, max);
Run Code Online (Sandbox Code Playgroud)
其中select_distribution定义为:
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>;
};
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.