Improve format_as safety

This commit is contained in:
Victor Zverovich
2023-03-19 06:51:47 -07:00
parent d9bc5f1320
commit 6549ffde8e
3 changed files with 24 additions and 41 deletions

View File

@@ -677,8 +677,11 @@ namespace test {
enum class scoped_enum_as_int {};
auto format_as(scoped_enum_as_int) -> int { return 42; }
enum class scoped_enum_as_string_view {};
auto format_as(scoped_enum_as_string_view) -> fmt::string_view { return "foo"; }
enum class scoped_enum_as_string {};
auto format_as(scoped_enum_as_string) -> fmt::string_view { return "foo"; }
auto format_as(scoped_enum_as_string) -> std::string { return "foo"; }
struct struct_as_int {};
auto format_as(struct_as_int) -> int { return 42; }
@@ -740,7 +743,8 @@ TEST(core_test, format_to) {
TEST(core_test, format_as) {
EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_int()), "42");
EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_string()), "foo");
// EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_string_view()), "foo");
// EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_string()), "foo");
EXPECT_EQ(fmt::format("{}", test::struct_as_int()), "42");
}

View File

@@ -1641,27 +1641,6 @@ TEST(format_test, format_explicitly_convertible_to_std_string_view) {
}
#endif
struct converible_to_anything {
template <typename T> operator T() const { return T(); }
};
FMT_BEGIN_NAMESPACE
template <> struct formatter<converible_to_anything> {
FMT_CONSTEXPR auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}
auto format(converible_to_anything, format_context& ctx)
-> decltype(ctx.out()) {
return format_to(ctx.out(), "foo");
}
};
FMT_END_NAMESPACE
TEST(format_test, format_convertible_to_anything) {
EXPECT_EQ("foo", fmt::format("{}", converible_to_anything()));
}
class Answer {};
FMT_BEGIN_NAMESPACE