Skip to content

Commit

Permalink
allow format_as() to format reference (fmtlib#3739)
Browse files Browse the repository at this point in the history
before this change, format_as() is unable to format a type which
has `auto format_as() -> const another_type&`, and `another_type`
is formattable. because `format_as_result` maps the result type
as it is, and the compiler refuses to compile
`static_cast<T*>(nullptr)`, where T is a reference type. but
it would be handy if we could use `format_as()` to format types
which, for instance, owns / inherit from a formattable type, and
delegate the formatter to these variables instead without creating
a copy of them.

in this change:

* instruct `format_as_result` to map the
  result type to the decayed type, so that `type` can be the decayed
  type of result type, and this also enables `type` to be formattable,
  as long as the decayed type is formattable.
* corresponding test is added to format-test.cc

Signed-off-by: Kefu Chai <tchaikov@gmail.com>
  • Loading branch information
tchaikov authored and happymonkey1 committed Apr 6, 2024
1 parent 3e3712d commit 42d1650
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 1 addition & 1 deletion include/fmt/core.h
Original file line number Diff line number Diff line change
Expand Up @@ -1332,7 +1332,7 @@ using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
template <typename T> struct format_as_result {
template <typename U,
FMT_ENABLE_IF(std::is_enum<U>::value || std::is_class<U>::value)>
static auto map(U*) -> decltype(format_as(std::declval<U>()));
static auto map(U*) -> remove_cvref_t<decltype(format_as(std::declval<U>()))>;
static auto map(...) -> void;

using type = decltype(map(static_cast<T*>(nullptr)));
Expand Down
8 changes: 8 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2173,13 +2173,21 @@ auto format_as(scoped_enum_as_string) -> std::string { return "foo"; }

struct struct_as_int {};
auto format_as(struct_as_int) -> int { return 42; }

struct struct_as_const_reference {
const std::string name = "foo";
};
auto format_as(const struct_as_const_reference& s) -> const std::string& {
return s.name;
}
} // namespace test

TEST(format_test, format_as) {
EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_int()), "42");
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");
EXPECT_EQ(fmt::format("{}", test::struct_as_const_reference()), "foo");
}

TEST(format_test, format_as_to_string) {
Expand Down

0 comments on commit 42d1650

Please sign in to comment.