From 22990323922889b7281bef7eea6ee7b42f4fcf9d Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Fri, 5 Oct 2018 13:21:29 -0700 Subject: [PATCH] Document how to write a formatter for a type hierarchy --- doc/api.rst | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/doc/api.rst b/doc/api.rst index 85c4d68b..355ecfdb 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -147,6 +147,35 @@ You can also reuse existing formatters, for example:: } }; +You can also write a formatter for a hierarchy of classes:: + + #include + #include + + struct A { + virtual ~A() {} + virtual std::string name() const { return "A"; } + }; + + struct B : A { + virtual std::string name() const { return "B"; } + }; + + template + struct fmt::formatter::value, char>> : + fmt::formatter { + template + auto format(const A& a, FormatCtx& ctx) { + return fmt::formatter::format(a.name(), ctx); + } + }; + + int main() { + B b; + A& a = b; + fmt::print("{}", a); // prints "B" + } + 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.