From 09fde7f4b86c21005121bea7ea9bbe39096294e5 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Sat, 22 Jan 2022 08:06:22 -0800 Subject: [PATCH] Add fmt::underlying for enum classes --- doc/api.rst | 2 ++ include/fmt/format.h | 16 ++++++++++++++++ test/format-test.cc | 8 +++++++- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/doc/api.rst b/doc/api.rst index c459e44068d9..07aea2c23d2e 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 9d713d561ed4..b4caec26a666 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 48d31e29335b..7b64abea1a93 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); }