Namespaces
Variants

std::meta::underlying_type

From cppreference.com
< cpp | meta
 
 
 
Reflection library
 
Reflection types and queries
Type properties
Type property queries
 
Defined in header <meta>
consteval std::meta::info underlying_type( std::meta::info r );
(since C++26)

If r represents a complete enumeration (enum) type T, returns a reflection of the underlying type of T.

If T is an incomplete enumeration type, the program is ill-formed.

Parameters

r - a reflection value

Return value

A reflection of an underlying integer type for reflected enumeration type r.

Exceptions

Throws std::meta::exception if r does not represent an enumeration type (or its type alias).

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).

Example

#include <meta>
#include <print>

enum E0 : long long {};
static_assert(underlying_type(^^E0) == ^^long long);

enum class E1 {};
static_assert(underlying_type(^^E1) == ^^int);

enum class E2 : unsigned {};
static_assert(underlying_type(^^E2) == ^^unsigned int);

enum struct E3 : short {};
static_assert(underlying_type(^^E3) == ^^short);

int main()
{
    // Unscoped enumeration without explicitly specified underlying
    // type has an implementation-defined “big enough” integral type.

    enum Cafe1 { drink1 = 0xC0FE };
    static constexpr auto u1{underlying_type(^^Cafe1)};
    std::println("{}", std::meta::display_string_of(u1)); // maybe “unsigned int”

    enum Cafe2 { drink2 = 0xC0FE'C0C0A };
    static constexpr auto u2{underlying_type(^^Cafe2)};
    std::println("{}", std::meta::display_string_of(u2)); // maybe “long unsigned int”
}

Possible output:

unsigned int
long unsigned int

See also

decltype specifier(C++11) obtains the type of an expression or an entity[edit]
checks if reflected type is an enumeration type
(function) [edit]
checks if reflection represents a scoped enumeration type
(function) [edit]
converts an enumeration to its underlying type
(function template) [edit]
obtains the underlying integer type for a given enumeration type
(class template) [edit]