使用模板提升随机性

时间:2011-07-11 17:56:27

标签: c++ boost boost-random

所以我试图将Boost.Random mt19937生成器与模板一起使用。我的c ++有点生疏,但从我所理解的一切(和文档一样,对于Boost来说,也不亚于模糊)它应该采用一个模板参数来指定它的返回类型(float / double)。

我现在不知道问题出在哪里......这一切都与<double><float>一起使用,并停止使用模板。

以下是代码:

template <class T>
class SpikingMatrixHelper {
public:
    SpikingMatrixHelper(const int seed);
    T generateNumber(const T, const T) const;
private:
    boost::mt19937 gen;
};

template <class T>
SpikingMatrixHelper<T>::SpikingMatrixHelper(const int seed) : gen(seed) {}

template <class T>
T SpikingMatrixHelper<T>::generateNumber(const T min, const T max) const {
    boost::uniform_real<T> dist(min, max);
    boost::variate_generator<boost::mt19937&, boost::uniform_real<T> > g(gen, dist);
    return g();
}

使用

进行variate_generator构建
/path/ [line] error: no matching function for call to ‘boost::variate_generator<boost::random::mersenne_twister<unsigned int, 32, 624, 397, 31, 2567483615u, 11, 7, 2636928640u, 15, 4022730752u, 18, 3346425566u>&, boost::uniform_real<double> >::variate_generator(const mt19937&, boost::uniform_real<double>&)’
/path/ [line] note: candidates are:
/usr/include/boost/random/variate_generator.hpp:133:3: note: boost::variate_generator<Engine, Distribution>::variate_generator(Engine, Distribution) [with Engine = boost::random::mersenne_twister<unsigned int, 32, 624, 397, 31, 2567483615u, 11, 7, 2636928640u, 15, 4022730752u, 18, 3346425566u>&, Distribution = boost::uniform_real<double>]
/usr/include/boost/random/variate_generator.hpp:133:3: note:   no known conversion for argument 1 from ‘const mt19937 {aka const boost::random::mersenne_twister<unsigned int, 32, 624, 397, 31, 2567483615u, 11, 7, 2636928640u, 15, 4022730752u, 18, 3346425566u>}’ to ‘boost::random::mersenne_twister<unsigned int, 32, 624, 397, 31, 2567483615u, 11, 7, 2636928640u, 15, 4022730752u, 18, 3346425566u>&’
/usr/include/boost/random/variate_generator.hpp:114:7: note: boost::variate_generator<boost::random::mersenne_twister<unsigned int, 32, 624, 397, 31, 2567483615u, 11, 7, 2636928640u, 15, 4022730752u, 18, 3346425566u>&, boost::uniform_real<double> >::variate_generator(const boost::variate_generator<boost::random::mersenne_twister<unsigned int, 32, 624, 397, 31, 2567483615u, 11, 7, 2636928640u, 15, 4022730752u, 18, 3346425566u>&, boost::uniform_real<double> >&)
/usr/include/boost/random/variate_generator.hpp:114:7: note:   candidate expects 1 argument, 2 provided

正如我所说,自从我完成c ++以来已经有一段时间了,Boost文档还有很多要求,所以任何提示都值得赞赏...

1 个答案:

答案 0 :(得分:1)

generateNumber不能const - 它会置换Mersenne Twister。制作mutable,或将函数设为非const