Scoped enum class
Type-safe enumerations.
Plain Enums Leak Names
A classic C-style enum dumps its names into the surrounding scope and silently converts to int. That makes name clashes and accidental comparisons easy.
- enum class fixes both problems.
- Values are scoped and strongly typed.
#include <iostream>
enum Color { Red, Green, Blue };
int main() {
Color c = Green;
int x = c; // implicit conversion to int
std::cout << x << "\n";
}Declaring a Scoped Enum
Add the class (or struct) keyword to make a scoped enumeration. Now you must qualify each value with the enum name.
#include <iostream>
enum class Color { Red, Green, Blue };
int main() {
Color c = Color::Green;
if (c == Color::Green) std::cout << "green\n";
}All lessons in this course
- Scoped enum class
- Unions and Their Risks
- std::variant
- std::visit