Is there a way to combine several enums into one?

Viewed 256

I have two enums:

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

I want to combine these two into one enum:

enum class Fruits
{
    //YellowFruits and RedFruits
};

So that it works like this:

enum class Fruits
{
    Banana,
    Lemon,
    Apple,
    Peach
};

But I can't find a way to do it. When looking for a solution, I found this answer: Combine enums c++. But the solutions in the answers there don't work for me. I want the new enum to work just as if I had created it with the values that it should take from other enums. Is there a way to do this?

1 Answers

It's not an enum class, but using C++20's using enum declaration, you can make a struct/class that combines the enums under one name. That would look like

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

Which outputs 1 as seen in this live example

Do note, Both Fruits::Peach and Fruits::Lemon will have the same value of 1 with this. If you need each enumeration to have a unique value, then you can't use this.

Related