Skip to content

Last updated:2026-10-12

C++ enum class Strongly Typed Enums

In Effective Modern C++, Item 10: Prefer scoped enums to unscoped enums advises replacing unscoped enums with scoped enum class.

For example:

enum Shape {circle,retangle};
auto circle = 10;  // error

The error above occurs because the two circles are in the same scope. For an enum, this is equivalent to:

#define circle 0
#define retangle 1
So defining circle again afterwards fails.

Therefore, no matter whether the enum names are the same, as long as any of their members coincide, there will be a problem. For example:

enum A {a,b};
enum B {c,a};
a appears twice; the error is reported at the a in enum B.

From the above we know that the enum name does nothing for scoping, which brings namespaces to mind, as in the following example:

// 在创建枚举时,将它们放在名称空间中,以便可以使用有意义的名称访问它们:
namespace EntityType {
    enum Enum {
        Ground = 0,
        Human,
        Aerial,
        Total
    };
}

void foo(EntityType::Enum entityType)
{
    if (entityType == EntityType::Ground) {
        /*code*/
    }
}
Name the namespace something meaningful and you get the desired effect.

But constantly using namespaces is inevitably too cumbersome; and if I do not want to use a namespace yet still want this effect, it becomes unsafe and unconstrained.

Therefore, after C++11, enum class was introduced.

enum class solves the problems of defining types for enum members, type safety, and scoping constraints. Back to the example above:

// enum class
enum class EntityType {
    Ground = 0,
    Human,
    Aerial,
    Total
};

void foo(EntityType entityType)
{
    if (entityType == EntityType::Ground) {
        /*code*/
    }
}
This is the idiom this section set out to explain: enum class.

Comments