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

Enable inheriting from formatter<std::string_view> #4055

Merged
merged 1 commit into from
Jul 14, 2024
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
12 changes: 9 additions & 3 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -3978,9 +3978,15 @@ struct formatter<T, Char, enable_if_t<detail::has_format_as<T>::value>>
}
};

#define FMT_FORMAT_AS(Type, Base) \
template <typename Char> \
struct formatter<Type, Char> : formatter<Base, Char> {}
#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()) { \
using base = formatter<Base, Char>; \
return base::format(value, ctx); \
} \
}

FMT_FORMAT_AS(signed char, int);
FMT_FORMAT_AS(unsigned char, unsigned);
Expand Down
14 changes: 14 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1650,6 +1650,20 @@ TEST(format_test, format_explicitly_convertible_to_std_string_view) {
EXPECT_EQ("'foo'",
fmt::format("{}", explicitly_convertible_to_std_string_view()));
}

struct convertible_to_std_string_view {
operator std::string_view() const noexcept { return "Hi there"; }
};
FMT_BEGIN_NAMESPACE
template <>
class formatter<convertible_to_std_string_view>
: public formatter<std::string_view> {};
FMT_END_NAMESPACE

TEST(format_test, format_implicitly_convertible_and_inherits_string_view) {
static_assert(fmt::is_formattable<convertible_to_std_string_view>{}, "");
EXPECT_EQ("Hi there", fmt::format("{}", convertible_to_std_string_view{}));
}
#endif

class Answer {};
Expand Down