From d52d13bffcc952e003aca074d2f87bdc757ea828 Mon Sep 17 00:00:00 2001 From: Anthony Van Herrewege Date: Thu, 8 Aug 2024 00:56:47 +0200 Subject: [PATCH] Improve compile-time formatting --- include/fmt/format.h | 20 +++++++++++--------- test/compile-test.cc | 1 + 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index 99596a1305fb..254dce18ba59 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -1003,7 +1003,7 @@ template struct fixed_string { } Char data[N] = {}; }; -#endif +#endif // FMT_USE_NONTYPE_TEMPLATE_ARGS // Converts a compile-time string to basic_string_view. template @@ -3912,19 +3912,21 @@ template struct formatter::value>> : formatter, Char> { template - auto format(const T& value, FormatContext& ctx) const -> decltype(ctx.out()) { + FMT_CONSTEXPR auto format(const T& value, FormatContext& ctx) const + -> decltype(ctx.out()) { auto&& val = format_as(value); // Make an lvalue reference for format. return formatter, Char>::format(val, ctx); } }; -#define FMT_FORMAT_AS(Type, Base) \ - template \ - struct formatter : formatter { \ - template \ - auto format(Type value, FormatContext& ctx) const -> decltype(ctx.out()) { \ - return formatter::format(value, ctx); \ - } \ +#define FMT_FORMAT_AS(Type, Base) \ + template \ + struct formatter : formatter { \ + template \ + FMT_CONSTEXPR auto format(Type value, FormatContext& ctx) const \ + -> decltype(ctx.out()) { \ + return formatter::format(value, ctx); \ + } \ } FMT_FORMAT_AS(signed char, int); diff --git a/test/compile-test.cc b/test/compile-test.cc index 5ba3edea2ebf..99006910ff71 100644 --- a/test/compile-test.cc +++ b/test/compile-test.cc @@ -334,6 +334,7 @@ TEST(compile_time_formatting_test, integer) { EXPECT_EQ("0X4A", test_format<5>(FMT_COMPILE("{:#X}"), 0x4a)); EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42)); + EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42l)); EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42ll)); EXPECT_EQ(" 42", test_format<6>(FMT_COMPILE("{:5}"), 42ull));