I'm using the Boost Random library to generate random numbers for a Monte Carlo simulation. In order to check my results, I'd like to be able to use different RNG engines for different runs. Ideally I'd like to use a command-line option to determine which RNG to use at run-time, instead of e.g. selecting the RNG at compile-time through a typedef.
Is there a base class T such that something like the following is possible; or if not, an obvious reason why not?
#include <boost/random.hpp>
int main()
{
unsigned char rng_choice = 0;
T* rng_ptr; // base_class pointer can point to any RNG from boost::random
switch(rng_choice)
{
case 0:
rng_ptr = new boost::random::mt19937;
break;
case 1:
rng_ptr = new boost::random::lagged_fibonacci607;
break;
}
boost::random::uniform_int_distribution<> dice_roll(1,6);
// Generate a variate from dice_roll using the engine defined by rng_ptr:
dice_roll(*rng_ptr);
delete rng_ptr;
return 0;
}
Simply use Boost.Function for type erasure.
Edit: A simple example.
#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
int main() {
boost::random::mt19937 gen;
boost::random::uniform_int_distribution<> dist(1, 6);
boost::function<int()> f;
f=boost::bind(dist,gen);
std::cout << f() << std::endl;
return 0;
}
Looking at the source code for mersenne twister for instance it seems there is no base class. It seems you will have to implement the class hierarchy you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With