Home > Blockchain >  How to pick up a random value from an enum class?
How to pick up a random value from an enum class?

Time:06-01

hello,

Been recently into C (C 14 to be precise), and I'me trying to get my way with enums, still have a bit of trouble figuring things out
Currently, trying to get a random value from an enum class that was constructed as such:

enum class Niveau {
  #define NIVEAU_DEF(NOM,VALEUR) NOM = VALEUR,
  #include "niveau.def"
  #undef NIVEAU_DEF
};

And here is the content of "niveau.def"

NIVEAU_DEF(I, 1)
NIVEAU_DEF(II, 2)
...
NIVEAU_DEF(IX, 9)
NIVEAU_DEF(X, 10)

Is it possible to pick up a random one of those enumerations using a method ? Or does this way of constructing an enum doesn't allow it?

CodePudding user response:

Since you have a XMacro already, you can just reuse it to create an array of the values and pick from it:

const Niveau niveau_vals[] = {
  #define NIVEAU_DEF(NOM,VALEUR) Niveau::VALEUR,
  #include "niveau.def"
  #undef NIVEAU_DEF
};

In newer versions of the language, you can make it a nice constexpr with std::array.

constexpr std::array niveau_vals = {
  #define NIVEAU_DEF(NOM,VALEUR) Niveau::VALEUR,
  #include "niveau.def"
  #undef NIVEAU_DEF
};
  • Related