diff --git a/doc/api.rst b/doc/api.rst index 2e7f6d6d..51ea81a1 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -95,8 +95,33 @@ containers such as ``std::vector``, :ref:`fmt/chrono.h ` for date and time formatting and :ref:`fmt/std.h ` for other standard library types. -To make a user-defined type formattable, specialize the ``formatter`` struct -template and implement ``parse`` and ``format`` methods:: +There are two ways to make a user-defined type formattable: providing a +``format_as`` function or specializing the ``formatter`` struct template. + +Use ``format_as`` if you want to make your type formattable as some other type +with the same format specifiers. The ``format_as`` function should take an +object of your type and return an object of a formattable type. It should be +defined in the same namespace as your type. + +Example (https://godbolt.org/z/r7vvGE1v7):: + + #include + + namespace kevin_namespacy { + enum class film { + house_of_cards, american_beauty, se7en = 7 + }; + auto format_as(film f) { return fmt::underlying(f); } + } + + int main() { + fmt::print("{}\n", kevin_namespacy::film::se7en); // prints "7" + } + +Using the specialization API is more comlex but gives you full control over +parsing and formatting. To use this method specialize the ``formatter`` struct +template for your type and implement ``parse`` and ``format`` methods. +For example:: #include @@ -228,26 +253,6 @@ If a type provides both a ``formatter`` specialization and an implicit conversion to a formattable type, the specialization takes precedence over the conversion. -For enums {fmt} also provides the ``format_as`` extension API. To format an enum -via this API define ``format_as`` that takes this enum and converts it to the -underlying type. ``format_as`` should be defined in the same namespace as the -enum. - -Example (https://godbolt.org/z/r7vvGE1v7):: - - #include - - namespace kevin_namespacy { - enum class film { - house_of_cards, american_beauty, se7en = 7 - }; - auto format_as(film f) { return fmt::underlying(f); } - } - - int main() { - fmt::print("{}\n", kevin_namespacy::film::se7en); // prints "7" - } - Named Arguments ---------------