Boost logo

Boost Users :

Subject: Re: [Boost-users] [Random] Passing an arbitrary uniform random number generator to a function
From: Joseph Gauterin (joseph.gauterin_at_[hidden])
Date: 2010-04-27 07:50:18


Looks like you need some sort of type erasure (Steve's suggestion uses
boost::function for that):

* Create a class that can be passed to uniform_real as a generator -
that is what Steve's runtime_generator class is for.
* Give runtime_generator a constructor that takes a single argument of
a template type, initialize min_ and max_ from that and store the
argument in impl (that will compile if the argument is a rng that
follows the correct conventions)
* Write the virtual function you wanted taking an argument of type
runtime_generator<double>& - but make it private
* Write a non-virtual public template function to wrap the rng

It's difficult to explain concisely - here's what the code should look
like (untested - just for explanation):

template<class ResultType>
class runtime_generator {
public:

  template <class T>
  explicit runtime_generator(T& rng)
    : min_(rng.min()), max_(rng.max()), impl(rng) {
  }

  ResultType min() const { return min_; }
  ResultType max() const { return max_; }
  ResultType operator()() { return impl(); }

private:
  ResultType min_, max_;
  boost::function<ResultType()> impl;
};

//in your class...
public:
template<class rng_t>
double foo(rng_t& urng)
{
  runtime_generator<double> rtRNG(urng);
  return foo_(rtRNG);
}

private:
virtual double foo_(runtime_generator<double> &urng)
{
  double x = uniform_real<double> (0.0, 10.0) (urng);
  double y = uniform_real<double> (5.0, 7.0) (urng);
  return (x*y);
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net