c++ - Selecting a valid random enum value in a general way -
let's have enumerated type e
.
enum class e : underlying_type_of_e { v1 = ue1, v2 = ue2, //... vn = uen }; typedef typename std::underlying_type<e>::type ue;
in general, not values of ue
valid values of e
, because can choose relationship between them. there general way of creating random, valid (named in definition, not assignable), values of e? this, example not work:
std::mt19937 m; std::uniform_int_distribution<ue> randomue(0, std::numeric_limits<ue>::max()); e e = static_cast<e>( randomue(m) );
because:
- value range may not start 0
- value range may not end @ std::numeric_limits::max()
- value range may not range @ - can select discrete values e ue, example {1, 3, 64, 272}.
given of enumerated values known @ compile-time, cannot imagine reason why in way dangerous, or error-prone.
as context of why want such thing - i'm working on genetic algorithm uses templated gene storage. now, use enums chromosomes , store them in std::vector<bool>
converted std::vector<enumt>
on demand. problem approach mutation flips random bits given probability. can cause problems, can produce invalid chromosomes unnamed enum values.
you can if you're prepared use preprocessor macro create both enum
type , meta-data it, it's minor hassle:
invoke variadic macro:
enum(e, v1 = ue1, v2 = ue2, // ... vn = uen);
create templated class
incrementing
successive variables initialised incrementingstatic
member default, can assigned whatever underlying type (e.g.int
).static incrementing<e, underlying> __va_args__; \
use values above initialise array
incrementing
values (which needoperator underlying() const
member).static const underlying values[] = { __va_args__ }; \
the values[]
array contains named enumeration values....
there's total overkill version of concept wrote years ago here, i'd recommend starting scratch given simple requirements.
Comments
Post a Comment