名前空間
変種
操作

std::underlying_type

提供: cppreference.com
< cpp‎ | types
 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
型サポート
型の性質
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(C++20未満)
(C++11)(C++20で非推奨)
(C++11)
型特性定数
メタ関数
(C++17)
定数評価文脈
サポートされている操作
関係と性質の問い合わせ
型変更
(C++11)(C++11)(C++11)
型変換
(C++11)
(C++11)
(C++17)
underlying_type
(C++11)
(C++11)(C++20未満)(C++17)
 
ヘッダ <type_traits> で定義
template< class T >
struct underlying_type;
(C++11以上)

T が完全な列挙型であれば、 T のベースとなる型を表すメンバ型 type が提供されます。

そうでなければ、動作は未定義です。

(C++20未満)

そうでなく、 T が列挙型でなければ、メンバ type は存在しません。 そうでなければ (T が不完全列挙型の場合)、プログラムは ill-formed です。

(C++20以上)

目次

[編集] メンバ型

名前 定義
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 incomplete enumeration types were allowed complete enumeration type required

[編集]

#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