名稱空間
變體
操作

std::underlying_type

來自 cppreference.com
< cpp‎ | 型別
 
 
超程式設計庫
型別特性
型別類別
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
型別屬性
(C++11)
(C++11)
(C++14)
(C++11)(C++26 中已棄用)
(C++11)(直到 C++20*)
(C++11)(C++20 中已棄用)
(C++11)
型別特性常量
元函式
(C++17)
支援的操作
關係與屬性查詢
型別修改
(C++11)(C++11)(C++11)
型別轉換
(C++11)(C++23 中已棄用)
(C++11)(C++23 中已棄用)
(C++11)
(C++11)(直到 C++20*)(C++17)

underlying_type
(C++11)
(C++11)
(C++17)
編譯時有理數算術
編譯時整數序列
 
定義於標頭檔案 <type_traits>
template< class T >
struct underlying_type;
(C++11 起)

如果 `T` 是一個完整的列舉型別(enum),則提供一個成員 typedef `type`,它命名 `T` 的底層型別。

否則,行為未定義。

(C++20 前)

否則,如果 `T` 不是列舉型別,則沒有成員 `type`。否則(`T` 是一個不完整的列舉型別),程式格式錯誤。

(C++20 起)

如果程式為 `std::underlying_type` 新增特化,則行為未定義。

目錄

[編輯] 成員型別

名稱 定義
型別 T 的底層型別

[編輯] 輔助型別

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

[編輯] 注意

每個列舉型別都有一個*底層型別*,可以是:

  1. 明確指定(有作用域和無作用域列舉);
  2. 省略,在這種情況下,對於有作用域列舉,它為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++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 2396 C++11 允許不完整的列舉型別 要求完整的列舉型別

[編輯] 參閱

(C++11)
檢查一個型別是否是列舉型別
(類模板) [編輯]
檢查一個型別是否是有作用域的列舉型別
(類模板) [編輯]
將列舉轉換為其底層型別
(函式模板) [編輯]