diff --git a/doc/api.rst b/doc/api.rst index ae70450a..2f2b345a 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -472,11 +472,11 @@ A ``std::variant`` is only formattable if every variant alternative is formattab #include std::variant v0{'x'}; - // Prints "<'x'>" + // Prints "variant('x')" fmt::print("{}", v0); - std::variant v1{}; - // Prints "< >" + std::variant v1; + // Prints "variant(monostate)" .. _compile-api: diff --git a/include/fmt/std.h b/include/fmt/std.h index 8b22570a..b9a0d30a 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -72,6 +72,7 @@ FMT_END_NAMESPACE #ifdef __cpp_lib_variant # include + FMT_BEGIN_NAMESPACE template struct formatter { template @@ -83,7 +84,7 @@ template struct formatter { auto format(const std::monostate&, FormatContext& ctx) const -> decltype(ctx.out()) { auto out = ctx.out(); - *out++ = ' '; + out = detail::write(out, "monostate"); return out; } }; @@ -134,27 +135,28 @@ template struct is_variant_formattable { detail::is_variant_formattable_::value; }; -template +template struct formatter< - VariantT, Char, + Variant, Char, std::enable_if_t, is_variant_formattable>>> { + is_variant_like, is_variant_formattable>>> { template FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { return ctx.begin(); } - template - auto format(const VariantT& value, FormatContext& ctx) const + template + auto format(const Variant& value, FormatContext& ctx) const -> decltype(ctx.out()) { auto out = ctx.out(); - *out++ = '<'; + + out = detail::write(out, "variant("); std::visit( [&](const auto& v) { out = detail::write_variant_alternative(out, v); }, value); - *out++ = '>'; + *out++ = ')'; return out; } }; diff --git a/test/std-test.cc b/test/std-test.cc index 0e34543c..02b5a591 100644 --- a/test/std-test.cc +++ b/test/std-test.cc @@ -37,16 +37,16 @@ TEST(std_test, thread_id) { TEST(std_test, variant) { #ifdef __cpp_lib_variant - EXPECT_EQ(fmt::format("{}", std::monostate{}), " "); + EXPECT_EQ(fmt::format("{}", std::monostate{}), "monostate"); using V0 = std::variant; V0 v0(42); V0 v1(1.5f); V0 v2("hello"); V0 v3('i'); - EXPECT_EQ(fmt::format("{}", v0), "<42>"); - EXPECT_EQ(fmt::format("{}", v1), "<1.5>"); - EXPECT_EQ(fmt::format("{}", v2), "<\"hello\">"); - EXPECT_EQ(fmt::format("{}", v3), "<'i'>"); + EXPECT_EQ(fmt::format("{}", v0), "variant(42)"); + EXPECT_EQ(fmt::format("{}", v1), "variant(1.5)"); + EXPECT_EQ(fmt::format("{}", v2), "variant(\"hello\")"); + EXPECT_EQ(fmt::format("{}", v3), "variant('i')"); struct unformattable {}; EXPECT_FALSE((fmt::is_formattable::value)); @@ -61,7 +61,7 @@ TEST(std_test, variant) { V1 v4{}; V1 v5{std::in_place_index<1>, "yes, this is variant"}; - EXPECT_EQ(fmt::format("{}", v4), "< >"); - EXPECT_EQ(fmt::format("{}", v5), "<\"yes, this is variant\">"); + EXPECT_EQ(fmt::format("{}", v4), "variant(monostate)"); + EXPECT_EQ(fmt::format("{}", v5), "variant(\"yes, this is variant\")"); #endif }