mirror of
https://github.com/fmtlib/fmt.git
synced 2024-11-19 11:14:41 +00:00
Expand FMT_FORMAT_AS to include implicit conversions (#4055)
Allows (for example) types convertible to std::string_view to inherit from the fmt::formatter<fmt::string_view> to work etc.
This commit is contained in:
parent
c9102619da
commit
5ef93a9f80
@ -3976,9 +3976,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);
|
||||
|
@ -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 {};
|
||||
|
Loading…
Reference in New Issue
Block a user