Skip to content

Commit

Permalink
Improve compile-time formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
AnthonyVH committed Aug 21, 2024
1 parent 1a79bbf commit d52d13b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
20 changes: 11 additions & 9 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -1003,7 +1003,7 @@ template <typename Char, size_t N> struct fixed_string {
}
Char data[N] = {};
};
#endif
#endif // FMT_USE_NONTYPE_TEMPLATE_ARGS

// Converts a compile-time string to basic_string_view.
template <typename Char, size_t N>
Expand Down Expand Up @@ -3912,19 +3912,21 @@ template <typename T, typename Char>
struct formatter<T, Char, enable_if_t<detail::has_format_as<T>::value>>
: formatter<detail::format_as_t<T>, Char> {
template <typename FormatContext>
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<detail::format_as_t<T>, Char>::format(val, ctx);
}
};

#define FMT_FORMAT_AS(Type, Base) \
template <typename Char> \
struct formatter<Type, Char> : formatter<Base, Char> { \
template <typename FormatContext> \
auto format(Type value, FormatContext& ctx) const -> decltype(ctx.out()) { \
return formatter<Base, Char>::format(value, ctx); \
} \
#define FMT_FORMAT_AS(Type, Base) \
template <typename Char> \
struct formatter<Type, Char> : formatter<Base, Char> { \
template <typename FormatContext> \
FMT_CONSTEXPR auto format(Type value, FormatContext& ctx) const \
-> decltype(ctx.out()) { \
return formatter<Base, Char>::format(value, ctx); \
} \
}

FMT_FORMAT_AS(signed char, int);
Expand Down
1 change: 1 addition & 0 deletions test/compile-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down

0 comments on commit d52d13b

Please sign in to comment.