std::underlying_type
来自cppreference.com
<tbody>
</tbody>
| 在标头 <type_traits> 定义
|
||
template< class T > struct underlying_type; |
(C++11 起) | |
若 T 是完整枚举类型,则提供指名 T 的底层类型的成员 typedef type。
|
否则,行为未定义。 |
(C++20 前) |
|
否则,若 |
(C++20 起) |
如果程序添加了 std::underlying_type 的特化,那么行为未定义。
成员类型
| 名称 | 定义 |
type
|
T 的底层类型
|
辅助类型
<tbody> </tbody> 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
<< "'e1' 的底层类型" << (e1_t ? "是 int" : "不是 int") << '\n'
<< "'e2' 的底层类型" << (e2_t ? "是 int" : "不是 int") << '\n'
<< "'e3' 的底层类型" << (e3_t ? "是 int" : "不是 int") << '\n'
<< "'e4' 的底层类型" << (e4_t ? "是 int" : "不是 int") << '\n';
}
可能的输出:
'e1' 的底层类型不是 int
'e2' 的底层类型是 int
'e3' 的底层类型不是 int
'e4' 的底层类型是 int
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 2396 | C++11 | 允许不完整枚举类型 | 要求完整枚举类型 |
参阅
(C++11) |
检查类型是否为枚举类型 (类模板) |
(C++23) |
检查类型是否为有作用域枚举类型 (类模板) |
(C++23) |
转换枚举为其底层类型 (函数模板) |