tags:

views:

88

answers:

1

Right now I'm generating a random enumerator using boost's random library. Basically I'm using an implicit conversion to specify the random generator's distribution, getting a random number, and then casting that back to the enumerated type.

Ex: (minColor and maxColor are parameters of the enumerated type)

boost::mt19937 randGen(std::time(0));
boost::uniform_int<> dist(minColor, maxColor);
boost::variate_generator< boost::mt19937&, boost::uniform_int<> >
    GetRand(randGen, dist);

return static_cast<Common::Color> (GetRand());

I'm curious whether boost's library supports anything like creating a distribution for an enumerated type, and thus returns a randomly selected enumerator. Something like...

boost::uniform<Common::Color> dist(minColor, maxColor);
A: 

Although it would make sense with C++0xs strongly typed enums, what you wan't isn't in general possible.

Enumeration terminology distinguishes the enumeration type and its underlying type which holds the enumeration values.
The standard mainly requires the underlying type to be big enough to hold all values, to not be larger as int if possible and that the size return by sizeof(someEnum) equals the size of its underlying type (§7.2.5 C++03).

Given only that and without restricting the style of how enums are used/declared, we know the size of the enumerations but not their signedness, which makes e.g. defining type-safe constructors taking min and max arguments impossible.

Sidenote:
I'd also personally find a distribution which is templated with an enumeration type somewhat misleading.
Is the distribution only defined for the enumeration values that are in the range?
Or is it defined for all values in the underlying type that are in the range?

Georg Fritzsche