Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

to_string supports types with format_as #3575

Merged
merged 1 commit into from
Aug 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -4287,7 +4287,8 @@ 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);
Expand All @@ -4312,6 +4313,12 @@ FMT_NODISCARD auto to_string(const basic_memory_buffer<Char, SIZE>& buf)
return std::basic_string<Char>(buf.data(), 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 {
return to_string(format_as(value));
}

namespace detail {

template <typename Char>
Expand Down
7 changes: 7 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2141,6 +2141,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