Make formatter override implicit conversion to a C string
This commit is contained in:
@@ -469,6 +469,10 @@ struct convertible_to_int {
|
||||
operator int() const { return 42; }
|
||||
};
|
||||
|
||||
struct convertible_to_c_string {
|
||||
operator const char*() const { return "foo"; }
|
||||
};
|
||||
|
||||
FMT_BEGIN_NAMESPACE
|
||||
template <> struct formatter<convertible_to_int> {
|
||||
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
|
||||
@@ -478,10 +482,21 @@ template <> struct formatter<convertible_to_int> {
|
||||
return std::copy_n("foo", 3, ctx.out());
|
||||
}
|
||||
};
|
||||
|
||||
template <> struct formatter<convertible_to_c_string> {
|
||||
auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
|
||||
return ctx.begin();
|
||||
}
|
||||
auto format(convertible_to_c_string, format_context& ctx)
|
||||
-> decltype(ctx.out()) {
|
||||
return std::copy_n("bar", 3, ctx.out());
|
||||
}
|
||||
};
|
||||
FMT_END_NAMESPACE
|
||||
|
||||
TEST(CoreTest, FormatterOverridesImplicitConversion) {
|
||||
EXPECT_EQ(fmt::format("{}", convertible_to_int()), "foo");
|
||||
EXPECT_EQ(fmt::format("{}", convertible_to_c_string()), "bar");
|
||||
}
|
||||
|
||||
namespace my_ns {
|
||||
|
||||
+5
-13
@@ -264,17 +264,13 @@ struct explicitly_convertible_to_string_like {
|
||||
}
|
||||
};
|
||||
|
||||
TEST(FormatterTest, FormatExplicitlyConvertibleToStringLike) {
|
||||
EXPECT_EQ("foo", fmt::format("{}", explicitly_convertible_to_string_like()));
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& os,
|
||||
explicitly_convertible_to_string_like) {
|
||||
return os << "bar";
|
||||
}
|
||||
|
||||
TEST(FormatterTest, FormatExplicitlyConvertibleToStringLikeIgnoreInserter) {
|
||||
EXPECT_EQ("foo", fmt::format("{}", explicitly_convertible_to_string_like()));
|
||||
TEST(FormatterTest, FormatExplicitlyConvertibleToStringLike) {
|
||||
EXPECT_EQ("bar", fmt::format("{}", explicitly_convertible_to_string_like()));
|
||||
}
|
||||
|
||||
#ifdef FMT_USE_STRING_VIEW
|
||||
@@ -284,17 +280,13 @@ struct explicitly_convertible_to_std_string_view {
|
||||
}
|
||||
};
|
||||
|
||||
TEST(FormatterTest, FormatExplicitlyConvertibleToStdStringView) {
|
||||
EXPECT_EQ("foo", fmt::format("{}", explicitly_convertible_to_string_like()));
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& os,
|
||||
explicitly_convertible_to_std_string_view) {
|
||||
return os << "bar";
|
||||
}
|
||||
|
||||
TEST(FormatterTest, FormatExplicitlyConvertibleToStdStringViewIgnoreInserter) {
|
||||
EXPECT_EQ("foo",
|
||||
fmt::format("{}", explicitly_convertible_to_std_string_view()));
|
||||
TEST(FormatterTest, FormatExplicitlyConvertibleToStdStringView) {
|
||||
EXPECT_EQ("bar", fmt::format("{}", explicitly_convertible_to_string_like()));
|
||||
}
|
||||
|
||||
#endif // FMT_USE_STRING_VIEW
|
||||
|
||||
Reference in New Issue
Block a user