Skip to content

Commit

Permalink
to_string supports types with format_as
Browse files Browse the repository at this point in the history
Signed-off-by: Vladislav Shchapov <[email protected]>
  • Loading branch information
phprus committed Aug 7, 2023
1 parent aeb6ad4 commit 5e5a31f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
11 changes: 10 additions & 1 deletion include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -4286,13 +4286,22 @@ auto join(Range&& range, string_view sep)
std::string answer = fmt::to_string(42);
\endrst
*/
template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value &&
!detail::has_format_as<T>::value)>
inline auto to_string(const T& value) -> std::string {
auto buffer = memory_buffer();
detail::write<char>(appender(buffer), value);
return {buffer.data(), buffer.size()};
}

template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value &&
detail::has_format_as<T>::value)>
inline auto to_string(const T& value) -> std::string {
auto buffer = memory_buffer();
detail::write<char>(appender(buffer), format_as(value));
return {buffer.data(), buffer.size()};
}

template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
FMT_NODISCARD inline auto to_string(T value) -> std::string {
// The buffer should be large enough to store the number including the sign
Expand Down
7 changes: 7 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2140,6 +2140,13 @@ TEST(format_test, format_as) {
EXPECT_EQ(fmt::format("{}", test::struct_as_int()), "42");
}

TEST(format_test, format_as_to_string) {
EXPECT_EQ(fmt::to_string(test::scoped_enum_as_int()), "42");
EXPECT_EQ(fmt::to_string(test::scoped_enum_as_string_view()), "foo");
EXPECT_EQ(fmt::to_string(test::scoped_enum_as_string()), "foo");
EXPECT_EQ(fmt::to_string(test::struct_as_int()), "42");
}

template <typename Char, typename T> bool check_enabled_formatter() {
static_assert(std::is_default_constructible<fmt::formatter<T, Char>>::value,
"");
Expand Down

0 comments on commit 5e5a31f

Please sign in to comment.