我有两个枚举:
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++。但是答案中的解决方案对我不起作用。我希望新的枚举能够正常工作,就像我使用它应该从其他枚举中获取的值创建它一样。有没有办法做到这一点?
答案 0 :(得分:3)
它不是 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);
}
在此 live example 中看到的输出 1
请注意,Fruits::Peach
和 Fruits::Lemon
将具有与此相同的 1
值。如果你需要每个枚举都有一个唯一的值,那么你就不能使用这个。