Boost logo

Boost Users :

Subject: Re: [Boost-users] Must cast unsigned int for random generator seed
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2008-10-18 17:23:50


AMDG

Phillip Jones wrote:
> I wanted to save the initial state of a random number generator and I
> ran into this issue -
>
> boost::mt19937 rng;
> unsigned int rseed = static_cast<unsigned int>(std::time(0));
> //rng.seed( rseed ); // This causes an error
> rng.seed( static_cast<unsigned int>(rseed) ); // ok
>
> The error is "mersenne_twister.hpp:103: error: `gen' cannot be used as
> a function".
>
> Obviously not a big problem since I can just use the cast and keep
> going. But is there a reason for this behavior? It seems odd that one
> must cast an unsigned int as an unsigned int to make it work

This is definitely a bug. Please file a trac ticket at svn.boost.org.
The following works.

#include <ctime>
#include <boost/random/mersenne_twister.hpp>

int main() {
    boost::mt19937 rng;
    boost::mt19937::result_type rseed =
static_cast<boost::mt19937::result_type>(std::time(0));
    rng.seed( rseed );
    rng.seed( static_cast<boost::mt19937::result_type>(rseed) );
}

The problem is that seed is overloaded like so:

void seed(UIntType value);
template<class Generator>
void seed(Generator & gen);

(UUnitType is boost::unit32_t)
If the argument is not exactly the same type that the mersenne_twister
uses, then the second overload is a better match. Casting to an
unsigned int
works, because the second overload can never match an rvalue.

In Christ,
Steven Watanabe


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