Namespaces
Variants

std:: underlying_type

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

underlying_type
(C++11)
(C++11)
(C++17)
Compile-time rational arithmetic
Compile-time integer sequences
定義先ヘッダ <type_traits>
template < class T >
struct underlying_type ;
(C++11以降)

T が完全な列挙型(enum)である場合、 T の基盤となる型を表すメンバーtypedef type を提供します。

それ以外の場合、動作は未定義です。

(C++20まで)

それ以外の場合、 T が列挙型でない場合、 type メンバーは存在しません。それ以外の場合( T が不完全な列挙型)、プログラムは不適格です。

(C++20以降)

プログラムが std::underlying_type に対する特殊化を追加する場合、動作は未定義です。

目次

メンバー型

名前 定義
type T の基盤となる型

ヘルパー型

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

注記

enumeration type underlying type を持ち、これは以下のいずれかになります

  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++規格に対して遡及的に適用されました。

DR Applied to Behavior as published Correct behavior
LWG 2396 C++11 不完全な列挙型が許可されていた 完全な列挙型が要求される

関連項目

(C++11)
型が列挙型かどうかをチェックする
(クラステンプレート)
型がスコープ付き列挙型かどうかをチェックする
(クラステンプレート)
列挙型をその基底型に変換する
(関数テンプレート)