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:
The error above occurs because the two circles are in the same scope. For an enum, this is equivalent to:
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:
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*/
}
}
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*/
}
}
Related Topics¶
- C++ Avoiding the Default Constructor | C++那些事
- C++ Class Initializer List Idiom | C++那些事
- C++ Prefer Class Templates over Function Templates | C++那些事
- C++ copy-and-swap Idiom | C++那些事
- C++ Dependency Injection | C++那些事
- C++ Header-Only vs Implementation Separation | C++那些事
- C++ Lazy Evaluation Idiom | C++那些事
- C++ Lookup Table Idiom | C++那些事
- C++ Member Pointers and Type Information | C++那些事
- C++ Mixin Idiom | C++那些事