Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::to_underlying

      From cppreference.com
      <cpp‎ |utility
       
       
      Utilities library
       
      Defined in header<utility>
      template<class Enum>
      constexprstd::underlying_type_t<Enum> to_underlying( Enum e)noexcept;
      (since C++23)

      Converts an enumeration to its underlying type. Equivalent toreturnstatic_cast<std::underlying_type_t<Enum>>(e);.

      Contents

      [edit]Parameters

      e - enumeration value to convert

      [edit]Return value

      The integer value of the underlying type ofEnum, converted frome.

      [edit]Notes

      std::to_underlying can be used to avoid converting an enumeration to an integer type other than its underlying type.

      Feature-test macroValueStdFeature
      __cpp_lib_to_underlying202102L(C++23)std::to_underlying

      [edit]Example

      Run this code
      #include <cstdint>#include <iomanip>#include <iostream>#include <type_traits>#include <utility> enumclass E1:char{ e};static_assert(std::is_same_v<char, decltype(std::to_underlying(E1::e))>); enumstruct E2:long{ e};static_assert(std::is_same_v<long, decltype(std::to_underlying(E2::e))>); enum E3:unsigned{ e};static_assert(std::is_same_v<unsigned, decltype(std::to_underlying(e))>); int main(){enumclass ColorMask:std::uint32_t{        red=0xFF, green=(red<<8), blue=(green<<8), alpha=(blue<<8)}; std::cout<<std::hex<<std::uppercase<<std::setfill('0')<<std::setw(8)<< std::to_underlying(ColorMask::red)<<'\n'<<std::setw(8)<< std::to_underlying(ColorMask::green)<<'\n'<<std::setw(8)<< std::to_underlying(ColorMask::blue)<<'\n'<<std::setw(8)<< std::to_underlying(ColorMask::alpha)<<'\n'; //  std::underlying_type_t<ColorMask> x = ColorMask::alpha; // Error: no known conversion[[maybe_unused]]std::underlying_type_t<ColorMask> y= std::to_underlying(ColorMask::alpha);// OK}

      Output:

      000000FF0000FF0000FF0000FF000000

      [edit]See also

      obtains the underlying integer type for a given enumeration type
      (class template)[edit]
      (C++11)
      checks if a type is an enumeration type
      (class template)[edit]
      checks if a type is a scoped enumeration type
      (class template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/to_underlying&oldid=158870"

      [8]ページ先頭

      ©2009-2025 Movatter.jp