Skip to content

Commit

Permalink
Add fmt::underlying for enum classes
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed Jan 22, 2022
1 parent 0014024 commit 09fde7f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 2 additions & 0 deletions doc/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,8 @@ Utilities
.. doxygenfunction:: fmt::ptr(const std::unique_ptr<T> &p) -> const void*
.. doxygenfunction:: fmt::ptr(const std::shared_ptr<T> &p) -> const void*

.. doxygenfunction:: fmt::underlying(Enum e) -> typename std::underlying_type<Enum>::type

.. doxygenfunction:: fmt::to_string(const T &value) -> std::string

.. doxygenfunction:: fmt::to_string_view(const Char *s) -> basic_string_view<Char>
Expand Down
16 changes: 16 additions & 0 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -2675,6 +2675,22 @@ template <typename T> auto ptr(const std::shared_ptr<T>& 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 <typename Enum>
constexpr auto underlying(Enum e) noexcept ->
typename std::underlying_type<Enum>::type {
return static_cast<typename std::underlying_type<Enum>::type>(e);
}

class bytes {
private:
string_view data_;
Expand Down
8 changes: 7 additions & 1 deletion test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 09fde7f

Please sign in to comment.