核心功能
- **自动推导底层类型**:无需显式指定枚举的底层类型(如 `static_cast<int>(e)`)。
- **提高代码可读性**:清晰表达转换意图。
- **安全性**:避免因枚举底层类型变更而导致的错误。
基本用法
cpp
#include <iostream>
#include <utility> // std::to_underlying
enum class Color : uint8_t {
Red = 1,
Green = 2,
Blue = 4
};
int main() {
Color c = Color::Green;
auto value = std::to_underlying(c); // 等价于 static_cast<uint8_t>(c)
std::cout << "Value: " << static_cast<int>(value) << std::endl; // 输出: 2
return 0;
}
技术细节
1. **函数原型**:
```cpp
template <typename E>
constexpr std::underlying_type_t<E> to_underlying(E e) noexcept;
```
- 参数 `e`:强类型枚举(enum class)或普通枚举的值。
- 返回值:枚举的底层整数类型(如 `int`、`uint8_t` 等)。
2. **头文件**:需要包含 `<utility>`。
3. **兼容性**:仅支持 C++23 及以上版本。若使用 earlier 版本,可手动实现:
```cpp
template <typename E>
constexpr auto to_underlying(E e) noexcept {
return static_cast<std::underlying_type_t<E>>(e);
}
```
应用场景
- **位掩码操作**:
```cpp
enum class Permissions : uint8_t {
Read = 1,
Write = 2,
Execute = 4
};
Permissions p = Permissions::Read | Permissions::Write;
uint8_t mask = std::to_underlying(p); // 获得整数掩码 3
```
- **序列化/反序列化**:
```cpp
void save_to_file(Color color) {
file.write(reinterpret_cast<const char*>(&std::to_underlying(color)), sizeof(Color));
}
```
注意事项
- **仅适用于枚举类型**:传入非枚举类型会导致编译错误。
- **保持类型一致性**:转换后的类型与枚举的底层类型严格一致。
如果需要在 C++23 之前的版本中使用类似功能,可自定义 `to_underlying` 函数模板,或继续使用 `static_cast`。