2

これがすでに議論されている場合は、ご容赦ください。テンプレート引数に応じて 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を返します。しかし、私が言ったように、それはダブルで動作します。私が間違っていることや欠けていることはありますか? ありがとうございました !

4

3 に答える 3

7

型特性と MPL を使用してボイラープレート コードを記述することを回避することもできます。

template <typename N>
N getRandom(N min, N max)
{
  typedef typename boost::mpl::if_<
    boost::is_floating_point<N>, // if we have a floating point type
    boost::uniform_real<>,       // use this, or
    boost::uniform_int<>         // else use this one
  >::type distro_type;

  timeval t;
  gettimeofday(&t,NULL);
  boost::mt19937 seed( (int)t.tv_sec );
  distro_type dist(min,max);
  boost::variate_generator<boost::mt19937&, distro_type > random(seed,dist);
  return random(); 
};
于 2011-06-24T16:29:35.130 に答える
7

引数0.0,5.0は float ではなく double です。それらをフロートにします:

float y = getRandom<float>(0.0f,5.0f);
于 2011-06-24T15:42:10.737 に答える
5

質問自体に実際に対処するのではなく、解決策:

特性クラスを使用して適切な配布タイプを取得してみませんか?

template<class T>
struct distribution
{ // general case, assuming T is of integral type
  typedef boost::uniform_int<> type;
};

template<>
struct distribution<float>
{ // float case
  typedef boost::uniform_real<> type;
};

template<>
struct distribution<double>
{ // double case
  typedef boost::uniform_real<> type;
};

このセットを使用すると、1つの一般的な機能を持つことができます。

template <typename N> N getRandom(N min, N max)
{
  typedef typename distribution<N>::type distro_type;

  timeval t;
  gettimeofday(&t,NULL);
  boost::mt19937 seed( (int)t.tv_sec );
  distro_type dist(min,max);
  boost::variate_generator<boost::mt19937&, distro_type > random(seed,dist);
  return random(); 
};
于 2011-06-24T15:44:42.073 に答える