cpp / intermediate
Snippet
Strongly Typed Enumerated Constants
Enum classes (scoped enums) provide better type safety than traditional enums by preventing implicit conversions to integers. Specifying the underlying type like 'unsigned char' optimizes memory usage.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>enum class SystemStatus : unsigned char {Idle = 0,Processing = 1,Error = 255};void checkStatus(SystemStatus status) {if (status == SystemStatus::Error) {std::cerr << "System failure detected!" << std::endl;}}
Breakdown
1
enum class SystemStatus : unsigned char
Defines a scoped enumeration restricted to an 8-bit unsigned integer type.
2
SystemStatus::Error
Accesses the constant using the scope resolution operator, preventing naming collisions.