Skip to content

Commit

Permalink
fix: support optional<T> with format_as(T) (fmtlib#3713)
Browse files Browse the repository at this point in the history
Formatting a std::optional<T> where T had a custom format_as(T) function failed to compile with clang,
due to set_debug_format being hidden by private inheritance. This fix makes the function available through a using clause.
  • Loading branch information
cptFracassa authored and happymonkey1 committed Apr 6, 2024
1 parent 660e8f1 commit a38ea21
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -4054,6 +4054,7 @@ struct formatter<T, Char, enable_if_t<detail::has_format_as<T>::value>>
: private formatter<detail::format_as_t<T>, Char> {
using base = formatter<detail::format_as_t<T>, Char>;
using base::parse;
using base::set_debug_format;

template <typename FormatContext>
auto format(const T& value, FormatContext& ctx) const -> decltype(ctx.out()) {
Expand Down
30 changes: 30 additions & 0 deletions test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,36 @@ TEST(std_test, optional) {
#endif
}

namespace my_nso {
enum class my_number {
one,
two,
};
auto format_as(my_number number) -> fmt::string_view {
return number == my_number::one ? "first" : "second";
}

class my_class {
public:
int av;

private:
friend auto format_as(const my_class& elm) -> std::string {
return fmt::to_string(elm.av);
}
};
} // namespace my_nso
TEST(std_test, optional_format_as) {
#ifdef __cpp_lib_optional
EXPECT_EQ(fmt::format("{}", std::optional<my_nso::my_number>{}), "none");
EXPECT_EQ(fmt::format("{}", std::optional{my_nso::my_number::one}),
"optional(\"first\")");
EXPECT_EQ(fmt::format("{}", std::optional<my_nso::my_class>{}), "none");
EXPECT_EQ(fmt::format("{}", std::optional{my_nso::my_class{7}}),
"optional(\"7\")");
#endif
}

struct throws_on_move {
throws_on_move() = default;

Expand Down

0 comments on commit a38ea21

Please sign in to comment.