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

Fix handling of types with custom formatters that are convertible to std::string_view #1451

Merged
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
4 changes: 3 additions & 1 deletion include/fmt/core.h
Original file line number Diff line number Diff line change
Expand Up @@ -878,7 +878,9 @@ template <typename Context> struct arg_mapper {
FMT_ENABLE_IF(
std::is_constructible<std_string_view<char_type>, T>::value &&
!std::is_constructible<basic_string_view<char_type>, T>::value &&
!is_string<T>::value)>
!is_string<T>::value &&
!has_formatter<T, Context>::value &&
!has_fallback_formatter<T, Context>::value)>
FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
return std_string_view<char_type>(val);
}
Expand Down
22 changes: 22 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1685,6 +1685,28 @@ TEST(FormatterTest, FormatStdStringView) {
EXPECT_EQ("test", format("{}", std::string_view("test")));
EXPECT_EQ("foo", format("{}", string_viewable()));
}

struct explicitly_convertible_to_std_string_view {
explicit operator std::string_view() const { return "foo"; }
};

namespace fmt {

template <>
struct formatter<explicitly_convertible_to_std_string_view>
: formatter<std::string_view> {
auto format(const explicitly_convertible_to_std_string_view& v,
format_context& ctx) {
return format_to(ctx.out(), "'{}'", std::string_view(v));
}
};

} // namespace fmt

TEST(FormatterTest, FormatExplicitlyConvertibleToStdStringView) {
EXPECT_EQ("'foo'",
fmt::format("{}", explicitly_convertible_to_std_string_view()));
}
#endif

FMT_BEGIN_NAMESPACE
Expand Down