std::underlying_type
来自 cppreference.cn
定义于头文件 <type_traits> |
||
template< class T > struct underlying_type; |
(自 C++11 起) | |
如果 T
是完整的枚举 (enum) 类型,则提供成员 typedef type
,其命名 T
的底层类型。
否则,行为未定义。 |
(直到 C++20) |
否则,如果 |
(自 C++20 起) |
如果程序为 std::underlying_type
添加特化,则行为未定义。
目录 |
[编辑] 成员类型
名称 | 定义 |
type
|
T 的底层类型 |
[编辑] 辅助类型
template< class T > using underlying_type_t = typename underlying_type<T>::type; |
(自 C++14 起) | |
[编辑] 注意
每个枚举类型都有一个底层类型,它可以是
- 显式指定(作用域和无作用域枚举均可);
- 省略,在这种情况下,对于作用域枚举,它是 int,对于无作用域枚举,它是能够表示枚举的所有值的实现定义的整数类型。
[编辑] 示例
运行此代码
#include <iostream> #include <type_traits> enum e1 {}; enum class e2 {}; enum class e3 : unsigned {}; enum class e4 : int {}; int main() { constexpr bool e1_t = std::is_same_v<std::underlying_type_t<e1>, int>; constexpr bool e2_t = std::is_same_v<std::underlying_type_t<e2>, int>; constexpr bool e3_t = std::is_same_v<std::underlying_type_t<e3>, int>; constexpr bool e4_t = std::is_same_v<std::underlying_type_t<e4>, int>; std::cout << "underlying type for 'e1' is " << (e1_t ? "int" : "non-int") << '\n' << "underlying type for 'e2' is " << (e2_t ? "int" : "non-int") << '\n' << "underlying type for 'e3' is " << (e3_t ? "int" : "non-int") << '\n' << "underlying type for 'e4' is " << (e4_t ? "int" : "non-int") << '\n'; }
可能的输出
underlying type for 'e1' is non-int underlying type for 'e2' is int underlying type for 'e3' is non-int underlying type for 'e4' is int
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 2396 | C++11 | 允许不完整的枚举类型 | 需要完整的枚举类型 |
[编辑] 参见
(C++11) |
检查类型是否为枚举类型 (类模板) |
(C++23) |
检查类型是否为作用域枚举类型 (类模板) |
(C++23) |
将枚举转换为其底层类型 (函数模板) |