diff --git a/doc/api.rst b/doc/api.rst index c459e440..07aea2c2 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -321,6 +321,8 @@ Utilities .. doxygenfunction:: fmt::ptr(const std::unique_ptr &p) -> const void* .. doxygenfunction:: fmt::ptr(const std::shared_ptr &p) -> const void* +.. doxygenfunction:: fmt::underlying(Enum e) -> typename std::underlying_type::type + .. doxygenfunction:: fmt::to_string(const T &value) -> std::string .. doxygenfunction:: fmt::to_string_view(const Char *s) -> basic_string_view diff --git a/include/fmt/format.h b/include/fmt/format.h index 9d713d56..b4caec26 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -2675,6 +2675,22 @@ template auto ptr(const std::shared_ptr& p) -> const void* { return p.get(); } +/** + \rst + Converts ``e`` to the underlying type. + + **Example**:: + + enum class color { red, green, blue }; + auto s = fmt::format("{}", fmt::underlying(color::red)); + \endrst + */ +template +constexpr auto underlying(Enum e) noexcept -> + typename std::underlying_type::type { + return static_cast::type>(e); +} + class bytes { private: string_view data_; diff --git a/test/format-test.cc b/test/format-test.cc index 48d31e29..7b64abea 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -1409,8 +1409,14 @@ TEST(format_test, format_pointer) { EXPECT_EQ("0x0", fmt::format("{}", nullptr)); } +enum class color { red, green, blue }; + +TEST(format_test, format_enum_class) { + EXPECT_EQ(fmt::format("{}", fmt::underlying(color::red)), "0"); +} + TEST(format_test, format_string) { - EXPECT_EQ("test", fmt::format("{0}", std::string("test"))); + EXPECT_EQ(fmt::format("{0}", std::string("test")), "test"); EXPECT_THROW((void)fmt::format(fmt::runtime("{:x}"), std::string("test")), fmt::format_error); }