c++ - 有没有办法将多个枚举合并为一个?

标签 c++

我有两个枚举:

enum class YellowFruits
{
    Banana,
    Lemon
};
enum class RedFruits
{
    Apple,
    Peach
};
我想将这两者合并为一个枚举:
enum class Fruits
{
    //YellowFruits and RedFruits
};
所以它的工作原理是这样的:
enum class Fruits
{
    Banana,
    Lemon,
    Apple,
    Peach
};
但我找不到办法做到这一点。
在寻找解决方案时,我找到了这个答案:Combine enums c++ .但是答案中的解决方案对我不起作用。我希望新的枚举能够正常工作,就像我使用它应该从其他枚举中获取的值创建它一样。有没有办法做到这一点?

最佳答案

这不是 enum class , 但使用 C++20 的 using enum declaration ,您可以制作 struct/class将枚举组合在一个名称下。那看起来像

enum class YellowFruits
{
    Banana,
    Lemon
};
enum class RedFruits
{
    Apple,
    Peach
};

struct Fruits
{
    using enum YellowFruits;
    using enum RedFruits;
};

int main()
{
    std::cout << static_cast<int>(Fruits::Peach);
}
哪个输出 1正如在此看到的 live example
请注意,两者都Fruits::PeachFruits::Lemon将具有相同的值 1有了这个。如果您需要每个枚举都具有唯一值,则不能使用它。

关于c++ - 有没有办法将多个枚举合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68385899/

相关文章:

c++ - 检测 32 位或 64 位 Windows

c++ - 作为此类对象的类变量

c++ - VS 2013 Community - 创建代码片段

c++ - 编译器声明没有匹配的调用函数,即使原型(prototype)中有一个

c++ - COleDateTime 在使用 time_t 构造时添加一个小时

c++ - 调用join时如何修复 `terminate called without an active exception`

c++ - 当维度大小不明确时传递多维数组函数

c++ - 启用从 `vector<const T>&` 到 `const vector<T>&` 的隐式转换

c++ - 组织和编写异常类的正确方法

C++ 名称与 typedef 别名和继承名称的冲突