[英]Encapsulate c++ Random Number Generator
I'm building something that requires me to 我正在建立一些需要我做的事情
template<D>
class DistributionAdapter {
public:
/**
* @return number generated by the distribution function.
*/
virtual D operator()(RANDOM_NUMBER_GENERATOR& rng) = 0;
};
RANDOM_NUMBER_GENERATOR is supposed to represent the class of random number generator in c++, either std::random_device or a pseudo random number generator. RANDOM_NUMBER_GENERATOR应该代表c ++中的随机数生成器类,即std :: random_device或伪随机数生成器。 Can someone tell me how should I approach this, I don't know if random number generator in c++ have a common base type
有人可以告诉我该如何处理,我不知道c ++中的随机数生成器是否具有通用基类型
It's not entirely clear what you're asking, but here is a fairly easy to use function returning uniformly distributed random integers within a particular range. 不清楚您要问的是什么,但这是一个相当容易使用的函数,用于返回特定范围内的均匀分布的随机整数。
#include <random>
// random number generator from Stroustrup:
// http://www.stroustrup.com/C++11FAQ.html#std-random
int rand_int(int low, int high)
{
static std::default_random_engine re {};
using Dist = std::uniform_int_distribution<int>;
static Dist uid {};
return uid(re, Dist::param_type{low,high});
}
Section § 26.5.1.3 of the standard describes the requirements for random number generators . 该标准的第26.5.1.3节描述了对随机数发生器的要求。
In particular, a generator must support the function call operator : 特别是,生成器必须支持函数调用运算符:
g() T Returns a value in the closed interval [ G::min() , G::max() ] .
g()T返回闭区间[G :: min(),G :: max()]中的值。 amortized constant
摊销常数
So, although there is no base class shared by every single generator, the standard guarantees that the operator()
will be present in each of them : you can call rng()
in your function. 因此,尽管每个生成器都没有共享基类,但是该标准保证在每个生成器中都存在
operator()
:您可以在函数中调用rng()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.