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