std::underlying_type

定义于头文件 <type_traits>
template< class T >
struct underlying_type;
(C++11 起)

T 是完整枚举类型,则提供指名 T 底层类型的成员 typedef type

否则,行为未定义。

目录

成员类型

名称 定义
type T 的底层类型

辅助类型

template< class T >
using underlying_type_t = typename underlying_type<T>::type;
(C++14 起)

注意

每个枚举类型都拥有底层类型,它可以是

1. 显式指定(有作用域和无作用域枚举均可)

2. 省略,该情况下对于有作用域枚举是 int ,或(对于无作用域枚举)是足以表示枚举所有值的实现定义的整数类型

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

DR 应用于 出版时的行为 正确行为
LWG 2396 C++11 允许不完整枚举类型 要求完整枚举类型

示例

#include <iostream>
#include <type_traits>
 
enum e1 {};
enum class e2: int {};
 
int main() {
    bool e1_type = std::is_same<
        unsigned
       ,typename std::underlying_type<e1>::type
    >::value; 
 
    bool e2_type = std::is_same<
        int
       ,typename std::underlying_type<e2>::type
    >::value;
 
    std::cout
    << "underlying type for 'e1' is " << (e1_type?"unsigned":"non-unsigned") << '\n'
    << "underlying type for 'e2' is " << (e2_type?"int":"non-int") << '\n';
}

输出:

underlying type for 'e1' is unsigned
underlying type for 'e2' is int

版本历史

  • (当前 | 先前 2017年12月9日 (六) 07:40Fruderica讨论 | 贡献 . . (1,732字节) (0). . (wording) (撤销)
  • 当前 | 先前 2017年7月8日 (六) 21:25Fruderica讨论 | 贡献. . (1,732字节) (-328). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 18:19P12bot讨论 | 贡献 . . (2,060字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:56P12bot讨论 | 贡献 . . (2,060字节) (-69). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 13:32P12bot讨论 | 贡献 . . (2,129字节) (+265). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 12:44P12讨论 | 贡献 . . (1,864字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,864字节) (-59). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 04:10P12讨论 | 贡献 . . (1,923字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,923字节) (+1,923). . (Translated from the English version using Google Translate)