Boost::随机和枚举类型
现在我正在使用 boost 的随机库生成一个随机枚举器。基本上,我使用隐式转换来指定随机生成器的分布,获取随机数,然后将其转换回枚举类型。
例如:(minColor 和 maxColor 是枚举类型的参数)
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());
我很好奇 boost 的库是否支持为枚举类型创建分布之类的功能,从而返回随机选择的枚举器。像...
boost::uniform<Common::Color> dist(minColor, maxColor);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管这对于 C++0xs 强类型枚举是有意义的,但您想要的通常是不可能的。
枚举术语区分枚举类型及其保存枚举值的底层类型。
该标准主要要求基础类型足够大以容纳所有值,如果可能的话不要大于
int
,并且sizeof(someEnum)
返回的大小等于其基础类型的大小(§7.2.5 C++03)。仅考虑到这一点,并且在不限制枚举使用/声明方式的情况下,我们知道枚举的大小,但不知道它们的符号,这使得例如定义类型安全构造函数采用 min 和 max 争论不可能。
旁注:
我个人还发现使用枚举类型模板化的发行版有些误导。
分布是否仅为范围内的枚举值定义?
或者它是为该范围内的基础类型中的所有值定义的吗?
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 bysizeof(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?