Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

enums

random

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?

like image 243
Simon Beureu Avatar asked Dec 18 '25 15:12

Simon Beureu


1 Answers

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
};

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!