sunkue
sunkue

Reputation: 288

Can I count how many kinds enum_class could be?

enum class COLOR_ : char
{
    RED,
    GREEN,
    BLUE,
    YELLOW
};
int monsternum{ kinds_of_COLOR_*3 };

my enum class COLOR_ may change a lot, during this project. I want monsternum must be +3 for each kind of COLOR_ how can I know the number of enum_class's kinds?

Upvotes: 4

Views: 73

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70287

Assuming your enum is indexed from 0 up to n-1 (where n is the number you want), the idiom I've seen used in the past is to include the count as an "extra" enum value.

enum class COLOR_ : char
{
    RED,
    GREEN,
    BLUE,
    YELLOW,
    COUNT
};

Then you can get it and simply cast to an int explicitly.

int monsternum{ (int)(COLOR_::COUNT)*3 };

If you add any colors above COUNT, then COUNT will have its index changed accordingly.

Upvotes: 3

Related Questions