The simplest way is probably to make global instances of the PRNG classes.
std::uniform_int_distribution<int> dist;
std::mt19937 rng((std::random_device()()));
struct foo
{
static int bar;
};
int foo::bar = dist(rng);
Of course, put the global objects and initialization in a .cpp file (thanks @AnonMail!).
Using the old (bad) random number facilities, you could use:
int foo::bar = (srand(time(0)), rand());
This is also not great because you've secretly seeded srand
which is sort of weird, and rand
is bad.
The (arguably) fun way is to do this:
int foo::bar = []() {std::uniform_int_distribution<int> dist; std::mt19937 mt((std::random_device()())); return dist(mt); }();
You use a lambda to create the variables and return the value, eliminating extra objects and putting it all on one line.
I realized I don't think I've seen a lambda used like this before, so I wasn't sure if it would work. My compiler seems fine with it, and it runs as intended, so my assumption would be this is correct.