如何将一个C ++ 11随机数生成器传递给一个函数? [英] How do I pass a C++11 random number generator to a function?
问题描述
它们都继承自一个基类吗?我必须使用模板吗?
Do they all inherit from a base class? Do I have to use templates?
(我指的是这些http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15319/ )
我现在正在这样做:
typedef std::mt19937 RNG;
,然后
class Chooser {
public:
Chooser(RNG& rng, uint n, uint min_choices, uint max_choices):
换句话说,我将引用传递给RNG。
In other words, I'm passing references to RNG. How would I pass in an arbitrary generator?
此外,我意识到这可能是一个不同的问题,但是如何将生成器传递给STL?
Also, I realize this is maybe a different question, but how do I pass the generator to STL?
std::random_shuffle(choices_.begin(), choices_.end(), rng);
似乎无效。
对传递生成器的解决方案:
solution to passing generator:
typedef std::ranlux64_base_01 RNG;
typedef std::mt19937 RNGInt;
解决方案传递给STL:
solution to passing to STL:
struct STL_RNG {
STL_RNG(RNGInt& rng): gen(rng) {}
RNGInt& gen;
int operator()(int n) { return std::uniform_int<int>(0, n)(gen); }
};
推荐答案
是一个有点意外),但它并不重要,因为这不是C ++函数如何工作。
They don't all inherit from a base (which is a little surprising), but it doesn't matter because that's not how C++ functors work.
对于任何一个给定类型的RNG,你得到正确的
For arbitrary RNGs of a single given type, you got it right as (now) posted.
如果您意味着,我如何定义一个接受任何随机数生成器作为参数的函数。
If you mean, how do I define a function which accepts any random number generator as an argument.
template< class RNG > // RNG may be a functor object of any type
int random_even_number( RNG &gen ) {
return (int) gen() * 2;
}
您不需要使用任何更多的模板,因为类型扣除。
You don't need to use any more templates than this, because of type deduction.
定义一个函数来接受不同的RNG是棘手的,因为语义上需要一个共同的基本类型。您需要定义一个基本类型。
Defining one function to accept different RNG's is trickier because semantically that requires having a common base type. You need to define a base type.
struct RNGbase {
virtual int operator() = 0;
virtual ~RGNBase() {};
};
template< class RNG >
struct SmartRNG : RNGBase {
RNG gen;
virtual int operator() {
return gen();
}
};
int random_even_number( RNGBase &gen ) { // no template
return (int) gen() * 2; // virtual dispatch
}
这篇关于如何将一个C ++ 11随机数生成器传递给一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!