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

Make format_arg() accept class hierarchies #547

Closed
wants to merge 1 commit into from
Closed
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
30 changes: 30 additions & 0 deletions doc/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,36 @@ Note in the example above the ``format_arg`` function ignores the contents of
``format_arg`` in :file:`fmt/time.h` for an advanced example of how to use
the ``format_str`` argument to customize the formatted output.

Note that this technique can be used for formatting class hierarchies too.::

namespace Local {
struct Parent {
Parent(int p_) : p(p_) {}
virtual void write(fmt::Writer& w) const {
w.write("Parent : p={}", p);
}
int p;
};

struct Child : Parent {
Child(int c_, int p_) : Parent(p_), c(c_) {}
virtual void write(fmt::Writer& w) const {
w.write("Child c={} : ", c);
Parent::write(w);
}
int c;
};

void format_arg(fmt::BasicFormatter<char> &f,
const char *&format_str, const Parent &p) {
p.write(f.writer());
}
}
Local::Child c(1,2);
Local::Parent &p = c;
fmt::print("via ref to base: {}\n", p);
fmt::print("direct to child: {}\n", c);

This section shows how to define a custom format function for a user-defined
type. The next section describes how to get ``fmt`` to use a conventional stream
output ``operator<<`` when one is defined for a user-defined type.
Expand Down
6 changes: 3 additions & 3 deletions fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -1255,9 +1255,9 @@ inline fmt::StringRef thousands_sep(...) { return ""; }
typedef int FMT_CONCAT_(Assert, __LINE__)[(cond) ? 1 : -1] FMT_UNUSED
#endif

template <typename Formatter, typename Char, typename T>
void format_arg(Formatter &, const Char *, const T &) {
FMT_STATIC_ASSERT(FalseType<T>::value,
template <typename Formatter /*, typename T> */>
void format_arg(Formatter&, /* const char*& fmt_string, const T& t* */...) {
FMT_STATIC_ASSERT(FalseType<Formatter>::value,
"Cannot format argument. To enable the use of ostream "
"operator<< include fmt/ostream.h. Otherwise provide "
"an overload of format_arg.");
Expand Down