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.