std::to_underlying 提供了一种安全、简洁的方式自动获取枚举类型的底层整型值,无需手动指定类型。1. 在 C++23 之前需用 static_cast 显式转换,必须知道底层类型,维护困难;2. std::to_underlying 结合 std::underlying_type_t 自动推导底层类型,提升泛型编程效率;3. 仅接受枚举类型,编译期检查增强安全性。该工具简化了枚举到整型的转换,尤其适用于模板代码,避免因枚举底层类型变更导致的错误,提高代码可读性和健壮性。

std::to_underlying 是 C++23 引入的一个便捷工具,用于安全、简洁地获取枚举类型(尤其是 enum class)的底层整型值。在 C++23 之前,开发者通常需要通过显式强制转换(static_cast)来获取枚举的整数值,这种方式虽然有效,但不够直观,也容易出错,尤其是在模板编程中。
为什么需要 std::to_underlying?
传统的做法是使用 static_cast 将枚举值转为其底层类型:
enum class Color : int {
Red = 1,
Green = 2,
Blue = 4
};
Color c = Color::Red;
int value = static_cast(c); // 手动指定底层类型
这种方法的问题在于:
- 必须手动知道并写出底层类型(如
int),一旦枚举定义改变,代码可能出错或不一致。 - 在泛型代码中,无法轻易获取枚举的底层类型,需要配合
std::underlying_type_t,写法繁琐。
std::to_underlying 的作用
std::to_underlying 提供了一种类型安全、简洁的方式,自动将枚举值转换为它的底层类型,无需手动指定类型。
#includeenum class Priority : uint8_t { Low = 1, Medium = 5, High = 10 }; Priority p = Priority::Medium; auto value = std::to_underlying(p); // 自动推导为 uint8_t
这里 value 的类型自动被推导为 uint8_t,与 Priority 的底层类型一致,无需显式书写。
在泛型编程中的优势
当编写模板函数处理任意枚举类型时,std::to_underlying 显得尤为有用:
templateconstexpr auto to_value(Enum e) { return std::to_underlying(e); }
这个函数适用于任何枚举类型,自动返回其底层整型值,无需特化或使用 std::enable_if 判断是否为枚举。
安全性和类型检查
std::to_underlying 只接受枚举类型作为参数。如果传入非枚举类型,编译器会报错,这比裸用 static_cast 更安全。
int x = 42; // auto v = std::to_underlying(x); // 编译错误:x 不是枚举类型
这种静态检查有助于避免误用,提升代码健壮性。
基本上就这些。std::to_underlying 让获取枚举底层值变得更安全、更简洁,尤其适合现代 C++ 的泛型和类型推导风格。










