Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ enum class with explicit values [closed]

Tags:

c++

By using normal enum it was a good practice to use explicit values to avoid unintentional inserting in the middle of an enum. It was quite essential since the enum items could be implicitly cast to integer.

What about enum class? Is it still a good practice to set explicit values or this is just an "outdated" behaviour?

E.g.:

enum class Animal
{
    Dog = 0,
    Cat = 1
};
like image 864
Tibor Takács Avatar asked Sep 14 '25 00:09

Tibor Takács


1 Answers

If I understand your question correctly, you are referring to binary compatibility. In the olden days when you couldn't forward declare an enum, you'd see something like this:

//Some header
enum Animal
{
    AnimalDog = 0,
    AnimalCat = 1
};

// Some other header, not #including the previous one    
void func(int an_animal); // Accepts an Aninal enum

And of course, if the enum was changed, then for the interest of binary compatibility, it was damn important to add the new enumerator at the end of the enumeration.

Does it change with scoped enums? Well, yes and no. You can foward declare a scoped enumeration.

//Some header
enum class Animal
{
    Dog = 0,
    Cat = 1
};

// Some other header, not #including the previous one    
enum class Animal;
void func(Animal);

So now you have some added type safety and scoping to avoid namespace pollution. But the same considerations about binary compatibility apply.

So I'd say yes. Keep doing what you are doing with scoped enumerations too.

like image 121
StoryTeller - Unslander Monica Avatar answered Sep 17 '25 03:09

StoryTeller - Unslander Monica