CKTIS / C++
std::to_underlying — convert an enumeration to its underlying type
std::to_underlying, declared in <utility>, converts an enumeration value to its exact underlying type. Available since C++23, it is constexpr and noexcept; it neither forces the result to int nor checks whether the value corresponds to a named enumerator.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <utility>
template<class T>
constexpr std::underlying_type_t<T> std::to_underlying(T value) noexcept;std::to_underlying(value), declared in <utility>, returns the numeric representation of an enumeration value. Its return type is std::underlying_type_t<T>, where T is the argument's type. It works with both enum and enum class; it is not a general-purpose function for converting arbitrary arguments to integers.
The result is defined as static_cast<std::underlying_type_t<T>>(value). Unlike static_cast<int>(value), the function preserves the exact underlying type, including its signedness, rather than forcing int. This is useful when passing an enumeration's numeric representation to another interface.
The function is constexpr, so it can participate in constant evaluation, and noexcept, so it does not throw exceptions. It does not check whether the supplied value corresponds to a named enumerator. It also does not perform the reverse conversion from a number to an enumeration.
In the example, Status has the explicit underlying type unsigned int. The assertions check the return type, the value 7u, and the noexcept property, while the program prints 7. C++23 support is required in both the compiler and standard library; a repository compiler flag alone does not attest operation in a production runtime.
Examples
#include <iostream>
#include <type_traits>
#include <utility>
enum class Status : unsigned int {
ready = 7,
done = 9
};
static_assert(std::is_same_v<
decltype(std::to_underlying(Status::ready)), unsigned int>);
static_assert(std::to_underlying(Status::ready) == 7u);
static_assert(noexcept(std::to_underlying(Status::ready)));
int main() {
std::cout << std::to_underlying(Status::ready) << '\n';
}
Result
7
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.