diff --git a/doc/api.rst b/doc/api.rst index 32be8e0b..2c9f803f 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -105,7 +105,7 @@ template and implement ``parse`` and ``format`` methods:: char presentation = 'f'; // Parses format specifications of the form ['f' | 'e']. - constexpr auto parse(format_parse_context& ctx) -> decltype(ctx.begin()) { + constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator { // [ctx.begin(), ctx.end()) is a character range that contains a part of // the format string starting from the format specifications to be parsed, // e.g. in @@ -134,8 +134,7 @@ template and implement ``parse`` and ``format`` methods:: // Formats the point p using the parsed format specification (presentation) // stored in this formatter. - template - auto format(const point& p, FormatContext& ctx) const -> decltype(ctx.out()) { + auto format(const point& p, format_context& ctx) const -> format_context::iterator { // ctx.out() is an output iterator to write to. return presentation == 'f' ? fmt::format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y) @@ -152,24 +151,33 @@ Then you can pass objects of type ``point`` to any formatting function:: You can also reuse existing formatters via inheritance or composition, for example:: + // color.h: #include enum class color {red, green, blue}; template <> struct fmt::formatter: formatter { // parse is inherited from formatter. - template - auto format(color c, FormatContext& ctx) const { - string_view name = "unknown"; - switch (c) { - case color::red: name = "red"; break; - case color::green: name = "green"; break; - case color::blue: name = "blue"; break; - } - return formatter::format(name, ctx); - } + + auto format(color c, format_context& ctx) const; }; + // color.cc: + #include "color.h" + #include + + auto fmt::formatter::format(color c, format_context& ctx) const { + string_view name = "unknown"; + switch (c) { + case color::red: name = "red"; break; + case color::green: name = "green"; break; + case color::blue: name = "blue"; break; + } + return formatter::format(name, ctx); + } + +Note that ``formatter::format`` is defined in ``fmt/format.h`` so +it has to be included in the source file. Since ``parse`` is inherited from ``formatter`` it will recognize all string format specifications, for example @@ -181,6 +189,7 @@ will return ``" blue"``. You can also write a formatter for a hierarchy of classes:: + // demo.h: #include #include @@ -196,12 +205,15 @@ You can also write a formatter for a hierarchy of classes:: template struct fmt::formatter::value, char>> : fmt::formatter { - template - auto format(const A& a, FormatCtx& ctx) const { + auto format(const A& a, format_context& ctx) const { return fmt::formatter::format(a.name(), ctx); } }; + // demo.cc: + #include "demo.h" + #include + int main() { B b; A& a = b;