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:

  1. value range may not start 0
  2. value range may not end @ std::numeric_limits::max()
  3. 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 incrementing static member default, can assigned whatever underlying type (e.g. int).

    static incrementing<e, underlying> __va_args__; \ 
  • use values above initialise array incrementing values (which need operator 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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -