From a7e356cc8070c911f6f12ebac6fd7188c77eda2c Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Fri, 14 Sep 2018 07:52:30 -0700 Subject: [PATCH] Update README.rst --- README.rst | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/README.rst b/README.rst index 422ac687..bd634a4a 100644 --- a/README.rst +++ b/README.rst @@ -108,24 +108,29 @@ Format strings can be checked at compile time: format_to(buf, "{:x}", 42); // replaces itoa(42, buffer, 16) // access the string using to_string(buf) or buf.data() -An object of any user-defined type for which there is an overloaded -:code:`std::ostream` insertion operator (``operator<<``) can be formatted: +Formatting of user-defined types is supported via a simple +`extension API `_: .. code:: c++ - #include "fmt/ostream.h" + #include "fmt/format.h" - class Date { - int year_, month_, day_; - public: - Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} + struct date { + int year, month, day; + }; - friend std::ostream &operator<<(std::ostream &os, const Date &d) { - return os << d.year_ << '-' << d.month_ << '-' << d.day_; + template <> + struct fmt::formatter { + template + constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } + + template + auto format(const date &d, FormatContext &ctx) { + return format_to(ctx.begin(), "{}-{}-{}", d.year, d.month, d.day); } }; - std::string s = fmt::format("The date is {}", Date(2012, 12, 9)); + std::string s = fmt::format("The date is {}", date{2012, 12, 9}); // s == "The date is 2012-12-9" You can create your own functions similar to `format