如何从枚举类中获取随机值?

发布于 2025-02-03 17:46:38 字数 404 浏览 2 评论 0原文

您好,

最近进入C ++(确切地说是C ++ 14),我试图通过枚举来解决自己的方式,仍然有点麻烦
当前,试图从这样构建的枚举类中获取一个随机值:

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

这是“ niveau.def”的内容,

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

是否可以使用方法来拿起这些枚举中的一个随机枚举?还是这种构建枚举的方式不允许?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨落成白 2025-02-10 17:46:39

由于您已经有了Xmacro,因此您可以将其重新使用以创建值的数组并从中挑选:

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

在语言的较新版本中,您可以将其作为std :: array的constexpr。 。

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

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
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文