これがすでに議論されている場合は、ご容赦ください。テンプレート引数に応じて boost::uniform_int と boost::uniform_real を使用し、同じ型を返す必要があるテンプレート関数があります。
template <typename N> N getRandom(int min, int max)
{
timeval t;
gettimeofday(&t,NULL);
boost::mt19937 seed((int)t.tv_sec);
boost::uniform_int<> dist(min, max);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > random(seed, dist);
return random();
}
//! partial specialization for real numbers
template <typename N> N getRandom(N min, N max)
{
timeval t;
gettimeofday(&t,NULL);
boost::mt19937 seed( (int)t.tv_sec );
boost::uniform_real<> dist(min,max);
boost::variate_generator<boost::mt19937&, boost::uniform_real<> > random(seed,dist);
return random();
}
これで、int、float、および double を使用して関数をテストしました。int では問題なく動作し、double では問題なく動作しますが、float では動作しません。float を int に変換するか、キャストの問題があるかのようです。私がこれを言っている理由は、私がそうするときです:
float y = getRandom<float>(0.0,5.0);
私はいつもintを返します。しかし、私が言ったように、それはダブルで動作します。私が間違っていることや欠けていることはありますか? ありがとうございました !