std::underlying_type

From cppreference.com
< cpp‎ | types
 
 
Utilities library
Type support (basic types, RTTI, type traits)
Dynamic memory management
Error handling
Program utilities
Variadic functions
Date and time
Function objects
(C++11)
Relational operators
Optional and any
(C++17)
(C++17)
Pairs and tuples
(C++11)
(C++17)
Swap, forward and move
(C++14)
(C++11)
(C++11)
Type operations
(C++11)
(C++17)
 
Type support
Basic types
Fundamental types
Fixed width integer types (C++11)
Numeric limits
C numeric limits interface
Runtime type information
Type traits
Type categories
(C++11)
(C++14)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Type properties
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++14)
(C++11)
Type trait constants
Metafunctions
(C++17)
(C++17)
(C++17)
Supported operations
Relationships and property queries
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Type modifications
(C++11)(C++11)(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
Type transformations
(C++11)
(C++11)
(C++11)
(C++11)
(C++17)
(C++11)
(C++11)
underlying_type
(C++11)
(C++11)
 
Defined in header <type_traits>
template< class T >
struct underlying_type;
(since C++11)

If T is a complete enumeration type, provides a member typedef type that names the underlying type of T.

Otherwise, the behavior is undefined.

Contents

[edit] Member types

Name Definition
type the underlying type of T

[edit] Helper types

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

[edit] Notes

Each enumeration type has an underlying type, which can be

1. Specified explicitly (both scoped and unscoped enumerations)

2. Omitted, in which case it is int for scoped enumerations or an implementation-defined integral type capable of representing all values of the enum (for unscoped enumerations)

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 2396 C++11 incomplete enumeration types were allowed complete enumeration type required

[edit] Example

#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';
}

Output:

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