So i have a Random object:
typedef unsigned int uint32;
class Random {
public:
Random() = default;
Random(std::mt19937::result_type seed) : eng(seed) {}
private:
uint32 DrawNumber();
std::mt19937 eng{std::random_device{}()};
std::uniform_int_distribution<uint32> uniform_dist{0, UINT32_MAX};
};
uint32 Random::DrawNumber()
{
return uniform_dist(eng);
}
What's the best way I can vary (through another function or otherwise) the upper bound of of the distribution?
(also willing to take advice on other style issues)
I'm making the
DrawNumber
functionpublic
for my example. You can provide an overload that takes an upper bound, and then pass a newuniform_int_distribution::param_type
touniform_int_distribution::operator()
The
param_type
can be constructed using the same arguments as the corresponding distribution.From N3337, §26.5.1.6/9 [rand.req.dist]
where
D
is the type of a random number distribution function object andP
is the type named byD
's associatedparam_type
Distribution objects are lightweight. Simply construct a new distribution when you need a random number. I use this approach in a game engine, and, after benchmarking, it's comparable to using good old
rand()
.Also, I've asked how to vary the range of distribution on GoingNative 2013 live stream, and Stephen T. Lavavej, a member of the standard committee, suggested to simply create new distributions, as it shouldn't be a performance issue.
Here's how I would write your code:
You can simply create a
std::uniform_int_distribution<uint32>::param_type
and modify the range using theparam()
method. You can cut down the template noise withdecltype
: