Strongly typed enumerations (enum class) provide better type safety and prevent implicit conversions to integral types. This design avoids many common errors associated with traditional enums, such as accidental comparisons with unrelated integers. However, there are situations where access to the raw underlying value is required - such as working with low-level APIs, serialization routines, logging systems, or legacy interfaces that expect integral types.
Consider the following strongly typed enumeration:
#include <iostream>
enum class UserStatus : unsigned char {
ACTIVE = 'A',
NOT_ACTIVE = 'N',
PENDING = 'P',
DELETED = 'D',
};
int main() {
auto status = static_cast<unsigned char>(UserStatus::ACTIVE);
std::cout << status << std::endl; // A
return 0;
}
Extracting the underlying enum value required an explicit static_cast to its base type. Although effective, this pattern added verbosity and reduced readability. In larger codebases, repeated casts can make intent less obvious and introduce maintenance concerns if the enum's underlying type changes.
Since C++23, we can use the std::to_underlying in the utility header. This standard utility function provides a clear and expressive way to retrieve the underlying enum value without manually specifying the type.
#include <iostream>
#include <utility>
enum class UserStatus : unsigned char {
ACTIVE = 'A',
NOT_ACTIVE = 'N',
PENDING = 'P',
DELETED = 'D',
};
int main() {
auto status = std::to_underlying(UserStatus::ACTIVE);
std::cout << status << std::endl; // A
return 0;
}
Leave a Comment
Cancel reply