/ externals / fmt / doc / api.rst
api.rst
  1  .. _string-formatting-api:
  2  
  3  *************
  4  API Reference
  5  *************
  6  
  7  The {fmt} library API consists of the following parts:
  8  
  9  * :ref:`fmt/core.h <core-api>`: the core API providing main formatting functions
 10    for ``char``/UTF-8 with C++20 compile-time checks and minimal dependencies
 11  * :ref:`fmt/format.h <format-api>`: the full format API providing additional
 12    formatting functions and locale support
 13  * :ref:`fmt/ranges.h <ranges-api>`: formatting of ranges and tuples
 14  * :ref:`fmt/chrono.h <chrono-api>`: date and time formatting
 15  * :ref:`fmt/std.h <std-api>`: formatters for standard library types
 16  * :ref:`fmt/compile.h <compile-api>`: format string compilation
 17  * :ref:`fmt/color.h <color-api>`: terminal color and text style
 18  * :ref:`fmt/os.h <os-api>`: system APIs
 19  * :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support
 20  * :ref:`fmt/args.h <args-api>`: dynamic argument lists
 21  * :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting
 22  * :ref:`fmt/xchar.h <xchar-api>`: optional ``wchar_t`` support 
 23  
 24  All functions and types provided by the library reside in namespace ``fmt`` and
 25  macros have prefix ``FMT_``.
 26  
 27  .. _core-api:
 28  
 29  Core API
 30  ========
 31  
 32  ``fmt/core.h`` defines the core API which provides main formatting functions
 33  for ``char``/UTF-8 with C++20 compile-time checks. It has minimal include
 34  dependencies for better compile times. This header is only beneficial when
 35  using {fmt} as a library (the default) and not in the header-only mode.
 36  It also provides ``formatter`` specializations for built-in and string types.
 37  
 38  The following functions use :ref:`format string syntax <syntax>`
 39  similar to that of Python's `str.format
 40  <https://docs.python.org/3/library/stdtypes.html#str.format>`_.
 41  They take *fmt* and *args* as arguments.
 42  
 43  *fmt* is a format string that contains literal text and replacement fields
 44  surrounded by braces ``{}``. The fields are replaced with formatted arguments
 45  in the resulting string. `~fmt::format_string` is a format string which can be
 46  implicitly constructed from a string literal or a ``constexpr`` string and is
 47  checked at compile time in C++20. To pass a runtime format string wrap it in
 48  `fmt::runtime`.
 49  
 50  *args* is an argument list representing objects to be formatted.
 51  
 52  .. _format:
 53  
 54  .. doxygenfunction:: format(format_string<T...> fmt, T&&... args) -> std::string
 55  .. doxygenfunction:: vformat(string_view fmt, format_args args) -> std::string
 56  
 57  .. doxygenfunction:: format_to(OutputIt out, format_string<T...> fmt, T&&... args) -> OutputIt
 58  .. doxygenfunction:: format_to_n(OutputIt out, size_t n, format_string<T...> fmt, T&&... args) -> format_to_n_result<OutputIt>
 59  .. doxygenfunction:: formatted_size(format_string<T...> fmt, T&&... args) -> size_t
 60  
 61  .. doxygenstruct:: fmt::format_to_n_result
 62     :members:
 63  
 64  .. _print:
 65  
 66  .. doxygenfunction:: fmt::print(format_string<T...> fmt, T&&... args)
 67  .. doxygenfunction:: fmt::vprint(string_view fmt, format_args args)
 68  
 69  .. doxygenfunction:: print(std::FILE *f, format_string<T...> fmt, T&&... args)
 70  .. doxygenfunction:: vprint(std::FILE *f, string_view fmt, format_args args)
 71  
 72  Compile-Time Format String Checks
 73  ---------------------------------
 74  
 75  Compile-time format string checks are enabled by default on compilers
 76  that support C++20 ``consteval``. On older compilers you can use the
 77  :ref:`FMT_STRING <legacy-checks>`: macro defined in ``fmt/format.h`` instead.
 78  
 79  Unused arguments are allowed as in Python's `str.format` and ordinary functions.
 80  
 81  .. doxygenclass:: fmt::basic_format_string
 82     :members:
 83  
 84  .. doxygentypedef:: fmt::format_string
 85  
 86  .. doxygenfunction:: fmt::runtime(string_view) -> runtime_format_string<>
 87  
 88  .. _udt:
 89  
 90  Formatting User-Defined Types
 91  -----------------------------
 92  
 93  The {fmt} library provides formatters for many standard C++ types.
 94  See :ref:`fmt/ranges.h <ranges-api>` for ranges and tuples including standard
 95  containers such as ``std::vector``, :ref:`fmt/chrono.h <chrono-api>` for date
 96  and time formatting and :ref:`fmt/std.h <std-api>` for other standard library
 97  types.
 98  
 99  There are two ways to make a user-defined type formattable: providing a
100  ``format_as`` function or specializing the ``formatter`` struct template.
101  
102  Use ``format_as`` if you want to make your type formattable as some other type
103  with the same format specifiers. The ``format_as`` function should take an
104  object of your type and return an object of a formattable type. It should be
105  defined in the same namespace as your type.
106  
107  Example (https://godbolt.org/z/r7vvGE1v7)::
108  
109    #include <fmt/format.h>
110  
111    namespace kevin_namespacy {
112    enum class film {
113      house_of_cards, american_beauty, se7en = 7
114    };
115    auto format_as(film f) { return fmt::underlying(f); }
116    }
117  
118    int main() {
119      fmt::print("{}\n", kevin_namespacy::film::se7en); // prints "7"
120    }
121  
122  Using the specialization API is more complex but gives you full control over
123  parsing and formatting. To use this method specialize the ``formatter`` struct
124  template for your type and implement ``parse`` and ``format`` methods.
125  For example::
126  
127    #include <fmt/core.h>
128  
129    struct point {
130      double x, y;
131    };
132  
133    template <> struct fmt::formatter<point> {
134      // Presentation format: 'f' - fixed, 'e' - exponential.
135      char presentation = 'f';
136  
137      // Parses format specifications of the form ['f' | 'e'].
138      constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator {
139        // [ctx.begin(), ctx.end()) is a character range that contains a part of
140        // the format string starting from the format specifications to be parsed,
141        // e.g. in
142        //
143        //   fmt::format("{:f} - point of interest", point{1, 2});
144        //
145        // the range will contain "f} - point of interest". The formatter should
146        // parse specifiers until '}' or the end of the range. In this example
147        // the formatter should parse the 'f' specifier and return an iterator
148        // pointing to '}'.
149        
150        // Please also note that this character range may be empty, in case of
151        // the "{}" format string, so therefore you should check ctx.begin()
152        // for equality with ctx.end().
153  
154        // Parse the presentation format and store it in the formatter:
155        auto it = ctx.begin(), end = ctx.end();
156        if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;
157  
158        // Check if reached the end of the range:
159        if (it != end && *it != '}') throw_format_error("invalid format");
160  
161        // Return an iterator past the end of the parsed range:
162        return it;
163      }
164  
165      // Formats the point p using the parsed format specification (presentation)
166      // stored in this formatter.
167      auto format(const point& p, format_context& ctx) const -> format_context::iterator {
168        // ctx.out() is an output iterator to write to.
169        return presentation == 'f'
170                  ? fmt::format_to(ctx.out(), "({:.1f}, {:.1f})", p.x, p.y)
171                  : fmt::format_to(ctx.out(), "({:.1e}, {:.1e})", p.x, p.y);
172      }
173    };
174  
175  Then you can pass objects of type ``point`` to any formatting function::
176  
177    point p = {1, 2};
178    std::string s = fmt::format("{:f}", p);
179    // s == "(1.0, 2.0)"
180  
181  You can also reuse existing formatters via inheritance or composition, for
182  example::
183  
184    // color.h:
185    #include <fmt/core.h>
186  
187    enum class color {red, green, blue};
188  
189    template <> struct fmt::formatter<color>: formatter<string_view> {
190      // parse is inherited from formatter<string_view>.
191  
192      auto format(color c, format_context& ctx) const;
193    };
194  
195    // color.cc:
196    #include "color.h"
197    #include <fmt/format.h>
198  
199    auto fmt::formatter<color>::format(color c, format_context& ctx) const {
200      string_view name = "unknown";
201      switch (c) {
202      case color::red:   name = "red"; break;
203      case color::green: name = "green"; break;
204      case color::blue:  name = "blue"; break;
205      }
206      return formatter<string_view>::format(name, ctx);
207    }
208  
209  Note that ``formatter<string_view>::format`` is defined in ``fmt/format.h`` so
210  it has to be included in the source file.
211  Since ``parse`` is inherited from ``formatter<string_view>`` it will recognize
212  all string format specifications, for example
213  
214  .. code-block:: c++
215  
216     fmt::format("{:>10}", color::blue)
217  
218  will return ``"      blue"``.
219  
220  You can also write a formatter for a hierarchy of classes::
221  
222    // demo.h:
223    #include <type_traits>
224    #include <fmt/core.h>
225  
226    struct A {
227      virtual ~A() {}
228      virtual std::string name() const { return "A"; }
229    };
230  
231    struct B : A {
232      virtual std::string name() const { return "B"; }
233    };
234  
235    template <typename T>
236    struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> :
237        fmt::formatter<std::string> {
238      auto format(const A& a, format_context& ctx) const {
239        return fmt::formatter<std::string>::format(a.name(), ctx);
240      }
241    };
242  
243    // demo.cc:
244    #include "demo.h"
245    #include <fmt/format.h>
246  
247    int main() {
248      B b;
249      A& a = b;
250      fmt::print("{}", a); // prints "B"
251    }
252  
253  Providing both a ``formatter`` specialization and a ``format_as`` overload is
254  disallowed.
255  
256  Named Arguments
257  ---------------
258  
259  .. doxygenfunction:: fmt::arg(const S&, const T&)
260  
261  Named arguments are not supported in compile-time checks at the moment.
262  
263  Argument Lists
264  --------------
265  
266  You can create your own formatting function with compile-time checks and small
267  binary footprint, for example (https://godbolt.org/z/vajfWEG4b):
268  
269  .. code:: c++
270  
271      #include <fmt/core.h>
272  
273      void vlog(const char* file, int line, fmt::string_view format,
274                fmt::format_args args) {
275        fmt::print("{}: {}: ", file, line);
276        fmt::vprint(format, args);
277      }
278  
279      template <typename... T>
280      void log(const char* file, int line, fmt::format_string<T...> format, T&&... args) {
281        vlog(file, line, format, fmt::make_format_args(args...));
282      }
283  
284      #define MY_LOG(format, ...) log(__FILE__, __LINE__, format, __VA_ARGS__)
285  
286      MY_LOG("invalid squishiness: {}", 42);
287  
288  Note that ``vlog`` is not parameterized on argument types which improves compile
289  times and reduces binary code size compared to a fully parameterized version.
290  
291  .. doxygenfunction:: fmt::make_format_args(const Args&...)
292  
293  .. doxygenclass:: fmt::format_arg_store
294     :members:
295  
296  .. doxygenclass:: fmt::basic_format_args
297     :members:
298  
299  .. doxygentypedef:: fmt::format_args
300  
301  .. doxygenclass:: fmt::basic_format_arg
302     :members:
303  
304  .. doxygenclass:: fmt::basic_format_parse_context
305     :members:
306  
307  .. doxygenclass:: fmt::basic_format_context
308     :members:
309  
310  .. doxygentypedef:: fmt::format_context
311  
312  .. _args-api:
313  
314  Dynamic Argument Lists
315  ----------------------
316  
317  The header ``fmt/args.h`` provides ``dynamic_format_arg_store``, a builder-like
318  API that can be used to construct format argument lists dynamically.
319  
320  .. doxygenclass:: fmt::dynamic_format_arg_store
321     :members:
322  
323  Compatibility
324  -------------
325  
326  .. doxygenclass:: fmt::basic_string_view
327     :members:
328  
329  .. doxygentypedef:: fmt::string_view
330  
331  .. _format-api:
332  
333  Format API
334  ==========
335  
336  ``fmt/format.h`` defines the full format API providing additional formatting
337  functions and locale support.
338  
339  Literal-Based API
340  -----------------
341  
342  The following user-defined literals are defined in ``fmt/format.h``.
343  
344  .. doxygenfunction:: operator""_a()
345  
346  Utilities
347  ---------
348  
349  .. doxygenfunction:: fmt::ptr(T p) -> const void*
350  .. doxygenfunction:: fmt::ptr(const std::unique_ptr<T, Deleter> &p) -> const void*
351  .. doxygenfunction:: fmt::ptr(const std::shared_ptr<T> &p) -> const void*
352  
353  .. doxygenfunction:: fmt::underlying(Enum e) -> typename std::underlying_type<Enum>::type
354  
355  .. doxygenfunction:: fmt::to_string(const T &value) -> std::string
356  
357  .. doxygenfunction:: fmt::join(Range &&range, string_view sep) -> join_view<detail::iterator_t<Range>, detail::sentinel_t<Range>>
358  
359  .. doxygenfunction:: fmt::join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel>
360  
361  .. doxygenfunction:: fmt::group_digits(T value) -> group_digits_view<T>
362  
363  .. doxygenclass:: fmt::detail::buffer
364     :members:
365  
366  .. doxygenclass:: fmt::basic_memory_buffer
367     :protected-members:
368     :members:
369  
370  System Errors
371  -------------
372  
373  {fmt} does not use ``errno`` to communicate errors to the user, but it may call
374  system functions which set ``errno``. Users should not make any assumptions
375  about the value of ``errno`` being preserved by library functions.
376  
377  .. doxygenfunction:: fmt::system_error
378  
379  .. doxygenfunction:: fmt::format_system_error
380  
381  Custom Allocators
382  -----------------
383  
384  The {fmt} library supports custom dynamic memory allocators.
385  A custom allocator class can be specified as a template argument to
386  :class:`fmt::basic_memory_buffer`::
387  
388      using custom_memory_buffer = 
389        fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
390  
391  It is also possible to write a formatting function that uses a custom
392  allocator::
393  
394      using custom_string =
395        std::basic_string<char, std::char_traits<char>, custom_allocator>;
396  
397      custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
398                            fmt::format_args args) {
399        auto buf = custom_memory_buffer(alloc);
400        fmt::vformat_to(std::back_inserter(buf), format_str, args);
401        return custom_string(buf.data(), buf.size(), alloc);
402      }
403  
404      template <typename ...Args>
405      inline custom_string format(custom_allocator alloc,
406                                  fmt::string_view format_str,
407                                  const Args& ... args) {
408        return vformat(alloc, format_str, fmt::make_format_args(args...));
409      }
410  
411  The allocator will be used for the output container only. Formatting functions
412  normally don't do any allocations for built-in and string types except for
413  non-default floating-point formatting that occasionally falls back on
414  ``sprintf``.
415  
416  Locale
417  ------
418  
419  All formatting is locale-independent by default. Use the ``'L'`` format
420  specifier to insert the appropriate number separator characters from the
421  locale::
422  
423    #include <fmt/core.h>
424    #include <locale>
425  
426    std::locale::global(std::locale("en_US.UTF-8"));
427    auto s = fmt::format("{:L}", 1000000);  // s == "1,000,000"
428  
429  ``fmt/format.h`` provides the following overloads of formatting functions that
430  take ``std::locale`` as a parameter. The locale type is a template parameter to
431  avoid the expensive ``<locale>`` include.
432  
433  .. doxygenfunction:: format(const Locale& loc, format_string<T...> fmt, T&&... args) -> std::string
434  .. doxygenfunction:: format_to(OutputIt out, const Locale& loc, format_string<T...> fmt, T&&... args) -> OutputIt
435  .. doxygenfunction:: formatted_size(const Locale& loc, format_string<T...> fmt, T&&... args) -> size_t
436  
437  .. _legacy-checks:
438  
439  Legacy Compile-Time Format String Checks
440  ----------------------------------------
441  
442  ``FMT_STRING`` enables compile-time checks on older compilers. It requires C++14
443  or later and is a no-op in C++11.
444  
445  .. doxygendefine:: FMT_STRING
446  
447  To force the use of legacy compile-time checks, define the preprocessor variable
448  ``FMT_ENFORCE_COMPILE_STRING``. When set, functions accepting ``FMT_STRING``
449  will fail to compile with regular strings.
450  
451  .. _ranges-api:
452  
453  Range and Tuple Formatting
454  ==========================
455  
456  The library also supports convenient formatting of ranges and tuples::
457  
458    #include <fmt/ranges.h>
459  
460    std::tuple<char, int, float> t{'a', 1, 2.0f};
461    // Prints "('a', 1, 2.0)"
462    fmt::print("{}", t);
463  
464  
465  NOTE: currently, the overload of ``fmt::join`` for iterables exists in the main
466  ``format.h`` header, but expect this to change in the future.
467  
468  Using ``fmt::join``, you can separate tuple elements with a custom separator::
469  
470    #include <fmt/ranges.h>
471  
472    std::tuple<int, char> t = {1, 'a'};
473    // Prints "1, a"
474    fmt::print("{}", fmt::join(t, ", "));
475  
476  .. _chrono-api:
477  
478  Date and Time Formatting
479  ========================
480  
481  ``fmt/chrono.h`` provides formatters for
482  
483  * `std::chrono::duration <https://en.cppreference.com/w/cpp/chrono/duration>`_
484  * `std::chrono::time_point
485    <https://en.cppreference.com/w/cpp/chrono/time_point>`_
486  * `std::tm <https://en.cppreference.com/w/cpp/chrono/c/tm>`_
487  
488  The format syntax is described in :ref:`chrono-specs`.
489  
490  **Example**::
491  
492    #include <fmt/chrono.h>
493  
494    int main() {
495      std::time_t t = std::time(nullptr);
496  
497      // Prints "The date is 2020-11-07." (with the current date):
498      fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
499  
500      using namespace std::literals::chrono_literals;
501  
502      // Prints "Default format: 42s 100ms":
503      fmt::print("Default format: {} {}\n", 42s, 100ms);
504  
505      // Prints "strftime-like format: 03:15:30":
506      fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
507    }
508  
509  .. doxygenfunction:: localtime(std::time_t time)
510  
511  .. doxygenfunction:: gmtime(std::time_t time)
512  
513  .. _std-api:
514  
515  Standard Library Types Formatting
516  =================================
517  
518  ``fmt/std.h`` provides formatters for:
519  
520  * `std::filesystem::path <https://en.cppreference.com/w/cpp/filesystem/path>`_
521  * `std::thread::id <https://en.cppreference.com/w/cpp/thread/thread/id>`_
522  * `std::monostate <https://en.cppreference.com/w/cpp/utility/variant/monostate>`_
523  * `std::variant <https://en.cppreference.com/w/cpp/utility/variant/variant>`_
524  * `std::optional <https://en.cppreference.com/w/cpp/utility/optional>`_
525  
526  Formatting Variants
527  -------------------
528  
529  A ``std::variant`` is only formattable if every variant alternative is formattable, and requires the
530  ``__cpp_lib_variant`` `library feature <https://en.cppreference.com/w/cpp/feature_test>`_.
531    
532  **Example**::
533  
534    #include <fmt/std.h>
535  
536    std::variant<char, float> v0{'x'};
537    // Prints "variant('x')"
538    fmt::print("{}", v0);
539  
540    std::variant<std::monostate, char> v1;
541    // Prints "variant(monostate)"
542  
543  .. _compile-api:
544  
545  Format String Compilation
546  =========================
547  
548  ``fmt/compile.h`` provides format string compilation enabled via the
549  ``FMT_COMPILE`` macro or the ``_cf`` user-defined literal. Format strings
550  marked with ``FMT_COMPILE`` or ``_cf`` are parsed, checked and converted into
551  efficient formatting code at compile-time. This supports arguments of built-in
552  and string types as well as user-defined types with ``format`` functions taking
553  the format context type as a template parameter in their ``formatter``
554  specializations. For example::
555  
556    template <> struct fmt::formatter<point> {
557      constexpr auto parse(format_parse_context& ctx);
558  
559      template <typename FormatContext>
560      auto format(const point& p, FormatContext& ctx) const;
561    };
562  
563  Format string compilation can generate more binary code compared to the default
564  API and is only recommended in places where formatting is a performance
565  bottleneck.
566  
567  .. doxygendefine:: FMT_COMPILE
568  
569  .. doxygenfunction:: operator""_cf()
570  
571  .. _color-api:
572  
573  Terminal Color and Text Style
574  =============================
575  
576  ``fmt/color.h`` provides support for terminal color and text style output.
577  
578  .. doxygenfunction:: print(const text_style &ts, const S &format_str, const Args&... args)
579  
580  .. doxygenfunction:: fg(detail::color_type)
581  
582  .. doxygenfunction:: bg(detail::color_type)
583  
584  .. doxygenfunction:: styled(const T& value, text_style ts)
585  
586  .. _os-api:
587  
588  System APIs
589  ===========
590  
591  .. doxygenclass:: fmt::ostream
592     :members:
593  
594  .. doxygenfunction:: fmt::windows_error
595     :members:
596  
597  .. _ostream-api:
598  
599  ``std::ostream`` Support
600  ========================
601  
602  ``fmt/ostream.h`` provides ``std::ostream`` support including formatting of
603  user-defined types that have an overloaded insertion operator (``operator<<``).
604  In order to make a type formattable via ``std::ostream`` you should provide a
605  ``formatter`` specialization inherited from ``ostream_formatter``::
606  
607    #include <fmt/ostream.h>
608  
609    struct date {
610      int year, month, day;
611  
612      friend std::ostream& operator<<(std::ostream& os, const date& d) {
613        return os << d.year << '-' << d.month << '-' << d.day;
614      }
615    };
616  
617    template <> struct fmt::formatter<date> : ostream_formatter {};
618  
619    std::string s = fmt::format("The date is {}", date{2012, 12, 9});
620    // s == "The date is 2012-12-9"
621  
622  .. doxygenfunction:: streamed(const T &)
623  
624  .. doxygenfunction:: print(std::ostream &os, format_string<T...> fmt, T&&... args)
625  
626  .. _printf-api:
627  
628  ``printf`` Formatting
629  =====================
630  
631  The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
632  The following functions use `printf format string syntax
633  <https://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
634  the POSIX extension for positional arguments. Unlike their standard
635  counterparts, the ``fmt`` functions are type-safe and throw an exception if an
636  argument type doesn't match its format specification.
637  
638  .. doxygenfunction:: printf(string_view fmt, const T&... args) -> int
639  
640  .. doxygenfunction:: fprintf(std::FILE *f, const S &fmt, const T&... args) -> int
641  
642  .. doxygenfunction:: sprintf(const S&, const T&...)
643  
644  .. _xchar-api:
645  
646  ``wchar_t`` Support
647  ===================
648  
649  The optional header ``fmt/xchar.h`` provides support for ``wchar_t`` and exotic
650  character types.
651  
652  .. doxygenstruct:: fmt::is_char
653  
654  .. doxygentypedef:: fmt::wstring_view
655  
656  .. doxygentypedef:: fmt::wformat_context
657  
658  .. doxygenfunction:: fmt::to_wstring(const T &value)
659  
660  Compatibility with C++20 ``std::format``
661  ========================================
662  
663  {fmt} implements nearly all of the `C++20 formatting library
664  <https://en.cppreference.com/w/cpp/utility/format>`_ with the following
665  differences:
666  
667  * Names are defined in the ``fmt`` namespace instead of ``std`` to avoid
668    collisions with standard library implementations.
669  * Width calculation doesn't use grapheme clusterization. The latter has been
670    implemented in a separate branch but hasn't been integrated yet.
671  * Most C++20 chrono types are not supported yet.