Incorporating boost random number generator as a class variable

孤街醉人 提交于 2021-01-28 06:55:06

问题


I'm trying to create a wrapper class for the boost random number generator, based on http://www.sitmo.com/article/generating-random-numbers-in-c-with-boost/. The problem is that boost uses templates and I don't know how to separate the declaration of GEN gen from the instantiation, like what can be done with separating DIST dist from dist = DIST(0, 1). Any advice appreciated.

fr.hpp:

#include <boost/random/variate_generator.hpp>
#include <boost/generator_iterator.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>

class FR {

   private:

     typedef boost::mt19937                     ENG;    // Mersenne Twister
     typedef boost::normal_distribution<double> DIST;   // Normal Distribution
     typedef boost::variate_generator<ENG,DIST> GEN;    // Variate generator

     ENG eng;
     DIST dist;
     GEN gen;

   public:
      FR();
};

fr.c:

#include "fr.hpp"

FR::FR() {
  dist = DIST(0, 1);
  gen = GEN(eng, dist);
}

which doesn't compile:

$ g++ -O3 -ggdb3 -Wall -c fr.cpp

fr.cpp: In constructor ‘FR::FR()’:
fr.cpp:3: error: no matching function for call to ‘boost::random::variate_generator<boost::random::mersenne_twister_engine<unsigned int, 32ul, 624ul, 397ul, 31ul, 2567483615u, 11ul, 4294967295u, 7ul, 2636928640u, 15ul, 4022730752u, 18ul, 1812433253u>, boost::random::normal_distribution<double> >::variate_generator()’

etc


回答1:


boost::variate_generator has no default constructor, so you need to use your constructor's initialization list:

FR::FR()
: dist(0,1), gen(eng,dist)
{}


来源:https://stackoverflow.com/questions/17691501/incorporating-boost-random-number-generator-as-a-class-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!