From 06c4c7f4a0fa53928a057782490b83ccd0f02ef5 Mon Sep 17 00:00:00 2001 From: Vladislav Shchapov Date: Mon, 7 Aug 2023 20:08:33 +0500 Subject: [PATCH] to_string supports types with format_as Signed-off-by: Vladislav Shchapov --- include/fmt/format.h | 9 ++++++++- test/format-test.cc | 7 +++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index e5bd8b110efe..a311fd9f9649 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -4287,7 +4287,8 @@ auto join(Range&& range, string_view sep) std::string answer = fmt::to_string(42); \endrst */ -template ::value)> +template ::value && + !detail::has_format_as::value)> inline auto to_string(const T& value) -> std::string { auto buffer = memory_buffer(); detail::write(appender(buffer), value); @@ -4312,6 +4313,12 @@ FMT_NODISCARD auto to_string(const basic_memory_buffer& buf) return std::basic_string(buf.data(), size); } +template ::value && + detail::has_format_as::value)> +inline auto to_string(const T& value) -> std::string { + return to_string(format_as(value)); +} + namespace detail { template diff --git a/test/format-test.cc b/test/format-test.cc index d148e743ea5f..dd3881716c95 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -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 bool check_enabled_formatter() { static_assert(std::is_default_constructible>::value, "");