Add support for ranges of types without formatters to join (#2262)

This commit is contained in:
Victor Zverovich 2021-05-05 06:50:52 -07:00
parent 4f0eadfce4
commit f0095ccd34
2 changed files with 24 additions and 7 deletions

View File

@ -3633,9 +3633,23 @@ template <typename It, typename Sentinel, typename Char>
struct formatter<arg_join<It, Sentinel, Char>, Char> {
private:
using value_type = typename std::iterator_traits<It>::value_type;
using context = buffer_context<Char>;
using mapper = detail::arg_mapper<context>;
template <typename T, FMT_ENABLE_IF(has_formatter<T, context>::value)>
static auto map(const T& value) -> const T& {
return value;
}
template <typename T, FMT_ENABLE_IF(!has_formatter<T, context>::value)>
static auto map(const T& value) -> decltype(mapper().map(value)) {
return mapper().map(value);
}
using formatter_type =
conditional_t<has_formatter<value_type, buffer_context<Char>>::value,
formatter<value_type, Char>,
conditional_t<is_formattable<value_type>::value,
formatter<remove_cvref_t<decltype(
map(std::declval<const value_type&>()))>,
Char>,
detail::fallback_formatter<value_type, Char>>;
formatter_type value_formatter_;
@ -3652,11 +3666,11 @@ struct formatter<arg_join<It, Sentinel, Char>, Char> {
auto it = value.begin;
auto out = ctx.out();
if (it != value.end) {
out = value_formatter_.format(*it++, ctx);
out = value_formatter_.format(map(*it++), ctx);
while (it != value.end) {
out = detail::copy_str<Char>(value.sep.begin(), value.sep.end(), out);
ctx.advance_to(out);
out = value_formatter_.format(*it++, ctx);
out = value_formatter_.format(map(*it++), ctx);
}
}
return out;

View File

@ -1609,6 +1609,8 @@ TEST(format_test, bytes) {
EXPECT_EQ(10, s.size());
}
enum test_enum { foo, bar };
TEST(format_test, join) {
using fmt::join;
int v1[3] = {1, 2, 3};
@ -1632,6 +1634,9 @@ TEST(format_test, join) {
EXPECT_EQ("(1, 2, 3)", fmt::format("({})", join(v1, ", ")));
EXPECT_EQ("(+01.20, +03.40)", fmt::format("({:+06.2f})", join(v2, ", ")));
auto v4 = std::vector<test_enum>{foo, bar, foo};
EXPECT_EQ("0 1 0", fmt::format("{}", join(v4, " ")));
}
#ifdef __cpp_lib_byte
@ -1763,9 +1768,7 @@ TEST(format_test, udl_pass_user_defined_object_as_lvalue) {
}
#endif // FMT_USE_USER_DEFINED_LITERALS
enum test_enum { A };
TEST(format_test, enum) { EXPECT_EQ("0", fmt::format("{}", A)); }
TEST(format_test, enum) { EXPECT_EQ("0", fmt::format("{}", foo)); }
TEST(format_test, formatter_not_specialized) {
static_assert(!fmt::has_formatter<fmt::formatter<test_enum>,