◐ Shell
clean mode source ↗

std::underlying_type - cppreference.com

提供: cppreference.com

<tbody> </tbody>

template< class T > struct underlying_type;

(C++11以上)

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

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

(C++20未満)

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

(C++20以上)

メンバ型

ヘルパー型

<tbody> </tbody>

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