3 The {fmt} library API consists of the following components:
5 - [`fmt/base.h`](#base-api): the base API providing main formatting functions
6 for `char`/UTF-8 with C++20 compile-time checks and minimal dependencies
7 - [`fmt/format.h`](#format-api): `fmt::format` and other formatting functions
8 as well as locale support
9 - [`fmt/ranges.h`](#ranges-api): formatting of ranges and tuples
10 - [`fmt/chrono.h`](#chrono-api): date and time formatting
11 - [`fmt/std.h`](#std-api): formatters for standard library types
12 - [`fmt/compile.h`](#compile-api): format string compilation
13 - [`fmt/color.h`](#color-api): terminal colors and text styles
14 - [`fmt/os.h`](#os-api): system APIs
15 - [`fmt/ostream.h`](#ostream-api): `std::ostream` support
16 - [`fmt/args.h`](#args-api): dynamic argument lists
17 - [`fmt/printf.h`](#printf-api): safe `printf`
18 - [`fmt/xchar.h`](#xchar-api): optional `wchar_t` support
20 All functions and types provided by the library reside in namespace `fmt`
21 and macros have prefix `FMT_`.
25 `fmt/base.h` defines the base API which provides main formatting functions
26 for `char`/UTF-8 with C++20 compile-time checks. It has minimal include
27 dependencies for better compile times. This header is only beneficial when
28 using {fmt} as a library (the default) and not in the header-only mode.
29 It also provides `formatter` specializations for the following types:
32 - `unsigned`, `unsigned long long`
33 - `float`, `double`, `long double`
36 - `const char*`, [`fmt::string_view`](#basic_string_view)
39 The following functions use [format string syntax](syntax.md) similar to that
40 of [str.format](https://docs.python.org/3/library/stdtypes.html#str.format)
41 in Python. They take *fmt* and *args* as arguments.
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`](#format_string) is a format
46 string which can be implicitly constructed from a string literal or a
47 `constexpr` string and is checked at compile time in C++20. To pass a runtime
48 format string wrap it in [`fmt::runtime`](#runtime).
50 *args* is an argument list representing objects to be formatted.
52 I/O errors are reported as [`std::system_error`](
53 https://en.cppreference.com/w/cpp/error/system_error) exceptions unless
56 ::: print(format_string<T...>, T&&...)
58 ::: print(FILE*, format_string<T...>, T&&...)
60 ::: println(format_string<T...>, T&&...)
62 ::: println(FILE*, format_string<T...>, T&&...)
64 ::: format_to(OutputIt&&, format_string<T...>, T&&...)
66 ::: format_to_n(OutputIt, size_t, format_string<T...>, T&&...)
68 ::: format_to_n_result
70 ::: formatted_size(format_string<T...>, T&&...)
73 ### Formatting User-Defined Types
75 The {fmt} library provides formatters for many standard C++ types.
76 See [`fmt/ranges.h`](#ranges-api) for ranges and tuples including standard
77 containers such as `std::vector`, [`fmt/chrono.h`](#chrono-api) for date and
78 time formatting and [`fmt/std.h`](#std-api) for other standard library types.
80 There are two ways to make a user-defined type formattable: providing a
81 `format_as` function or specializing the `formatter` struct template.
83 Use `format_as` if you want to make your type formattable as some other
84 type with the same format specifiers. The `format_as` function should
85 take an object of your type and return an object of a formattable type.
86 It should be defined in the same namespace as your type.
88 Example ([run](https://godbolt.org/z/nvME4arz8)):
90 #include <fmt/format.h>
92 namespace kevin_namespacy {
95 house_of_cards, american_beauty, se7en = 7
98 auto format_as(film f) { return fmt::underlying(f); }
103 fmt::print("{}\n", kevin_namespacy::film::se7en); // Output: 7
106 Using specialization is more complex but gives you full control over
107 parsing and formatting. To use this method specialize the `formatter`
108 struct template for your type and implement `parse` and `format`
111 The recommended way of defining a formatter is by reusing an existing
112 one via inheritance or composition. This way you can support standard
113 format specifiers without implementing them yourself. For example:
117 #include <fmt/base.h>
119 enum class color {red, green, blue};
121 template <> struct fmt::formatter<color>: formatter<string_view> {
122 // parse is inherited from formatter<string_view>.
124 auto format(color c, format_context& ctx) const
125 -> format_context::iterator;
132 #include <fmt/format.h>
134 auto fmt::formatter<color>::format(color c, format_context& ctx) const
135 -> format_context::iterator {
136 string_view name = "unknown";
138 case color::red: name = "red"; break;
139 case color::green: name = "green"; break;
140 case color::blue: name = "blue"; break;
142 return formatter<string_view>::format(name, ctx);
146 Note that `formatter<string_view>::format` is defined in `fmt/format.h`
147 so it has to be included in the source file. Since `parse` is inherited
148 from `formatter<string_view>` it will recognize all string format
149 specifications, for example
152 fmt::format("{:>10}", color::blue)
155 will return `" blue"`.
157 <!-- The experimental `nested_formatter` provides an easy way of applying a
158 formatter to one or more subobjects.
162 #include <fmt/format.h>
169 struct fmt::formatter<point> : nested_formatter<double> {
170 auto format(point p, format_context& ctx) const {
171 return write_padded(ctx, [=](auto out) {
172 return format_to(out, "({}, {})", this->nested(p.x),
179 fmt::print("[{:>20.2f}]", point{1, 2});
186 Notice that fill, align and width are applied to the whole object which
187 is the recommended behavior while the remaining specifiers apply to
190 In general the formatter has the following form:
192 template <> struct fmt::formatter<T> {
193 // Parses format specifiers and stores them in the formatter.
195 // [ctx.begin(), ctx.end()) is a, possibly empty, character range that
196 // contains a part of the format string starting from the format
197 // specifications to be parsed, e.g. in
199 // fmt::format("{:f} continued", ...);
201 // the range will contain "f} continued". The formatter should parse
202 // specifiers until '}' or the end of the range. In this example the
203 // formatter should parse the 'f' specifier and return an iterator
205 constexpr auto parse(format_parse_context& ctx)
206 -> format_parse_context::iterator;
208 // Formats value using the parsed format specification stored in this
209 // formatter and writes the output to ctx.out().
210 auto format(const T& value, format_context& ctx) const
211 -> format_context::iterator;
214 It is recommended to at least support fill, align and width that apply
215 to the whole object and have the same semantics as in standard
218 You can also write a formatter for a hierarchy of classes:
222 #include <type_traits>
223 #include <fmt/core.h>
227 virtual std::string name() const { return "A"; }
231 virtual std::string name() const { return "B"; }
234 template <typename T>
235 struct fmt::formatter<T, std::enable_if_t<std::is_base_of_v<A, T>, char>> :
236 fmt::formatter<std::string> {
237 auto format(const A& a, format_context& ctx) const {
238 return formatter<std::string>::format(a.name(), ctx);
246 #include <fmt/format.h>
251 fmt::print("{}", a); // Output: B
255 Providing both a `formatter` specialization and a `format_as` overload is
258 ::: basic_format_parse_context
264 ### Compile-Time Checks
266 Compile-time format string checks are enabled by default on compilers
267 that support C++20 `consteval`. On older compilers you can use the
268 [FMT_STRING](#legacy-checks) macro defined in `fmt/format.h` instead.
270 Unused arguments are allowed as in Python's `str.format` and ordinary functions.
272 ::: basic_format_string
276 ::: runtime(string_view)
280 ::: arg(const Char*, const T&)
282 Named arguments are not supported in compile-time checks at the moment.
286 You can create your own formatting function with compile-time checks and
287 small binary footprint, for example ([run](https://godbolt.org/z/b9Pbasvzc)):
290 #include <fmt/format.h>
292 void vlog(const char* file, int line,
293 fmt::string_view fmt, fmt::format_args args) {
294 fmt::print("{}: {}: {}", file, line, fmt::vformat(fmt, args));
297 template <typename... T>
298 void log(const char* file, int line,
299 fmt::format_string<T...> fmt, T&&... args) {
300 vlog(file, line, fmt, fmt::make_format_args(args...));
303 #define MY_LOG(fmt, ...) log(__FILE__, __LINE__, fmt, __VA_ARGS__)
305 MY_LOG("invalid squishiness: {}", 42);
308 Note that `vlog` is not parameterized on argument types which improves
309 compile times and reduces binary code size compared to a fully
310 parameterized version.
312 ::: make_format_args(T&...)
314 ::: basic_format_args
322 ::: basic_string_view
328 `fmt/format.h` defines the full format API providing additional
329 formatting functions and locale support.
332 ::: format(format_string<T...>, T&&...)
334 ::: vformat(string_view, format_args)
344 ::: to_string(const T&)
350 ::: basic_memory_buffer
354 {fmt} does not use `errno` to communicate errors to the user, but it may
355 call system functions which set `errno`. Users should not make any
356 assumptions about the value of `errno` being preserved by library
361 ::: format_system_error
363 ### Custom Allocators
365 The {fmt} library supports custom dynamic memory allocators. A custom
366 allocator class can be specified as a template argument to
367 [`fmt::basic_memory_buffer`](#basic_memory_buffer):
369 using custom_memory_buffer =
370 fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>;
372 It is also possible to write a formatting function that uses a custom
375 using custom_string =
376 std::basic_string<char, std::char_traits<char>, custom_allocator>;
378 custom_string vformat(custom_allocator alloc, fmt::string_view format_str,
379 fmt::format_args args) {
380 auto buf = custom_memory_buffer(alloc);
381 fmt::vformat_to(std::back_inserter(buf), format_str, args);
382 return custom_string(buf.data(), buf.size(), alloc);
385 template <typename ...Args>
386 inline custom_string format(custom_allocator alloc,
387 fmt::string_view format_str,
388 const Args& ... args) {
389 return vformat(alloc, format_str, fmt::make_format_args(args...));
392 The allocator will be used for the output container only. Formatting
393 functions normally don't do any allocations for built-in and string
394 types except for non-default floating-point formatting that occasionally
395 falls back on `sprintf`.
399 All formatting is locale-independent by default. Use the `'L'` format
400 specifier to insert the appropriate number separator characters from the
403 #include <fmt/core.h>
406 std::locale::global(std::locale("en_US.UTF-8"));
407 auto s = fmt::format("{:L}", 1000000); // s == "1,000,000"
409 `fmt/format.h` provides the following overloads of formatting functions
410 that take `std::locale` as a parameter. The locale type is a template
411 parameter to avoid the expensive `<locale>` include.
413 ::: format(const Locale&, format_string<T...>, T&&...)
415 ::: format_to(OutputIt, const Locale&, format_string<T...>, T&&...)
417 ::: formatted_size(const Locale&, format_string<T...>, T&&...)
419 <a id="legacy-checks"></a>
420 ### Legacy Compile-Time Checks
422 `FMT_STRING` enables compile-time checks on older compilers. It requires
423 C++14 or later and is a no-op in C++11.
427 To force the use of legacy compile-time checks, define the preprocessor
428 variable `FMT_ENFORCE_COMPILE_STRING`. When set, functions accepting
429 `FMT_STRING` will fail to compile with regular strings.
431 <a id="ranges-api"></a>
432 ## Range and Tuple Formatting
434 `fmt/ranges.h` provides formatting support for ranges and tuples:
436 #include <fmt/ranges.h>
438 fmt::print("{}", std::tuple<char, int>{'a', 42});
441 Using `fmt::join`, you can separate tuple elements with a custom separator:
443 #include <fmt/ranges.h>
445 auto t = std::tuple<int, char>{1, 'a'};
446 fmt::print("{}", fmt::join(t, ", "));
449 ::: join(Range&&, string_view)
451 ::: join(It, Sentinel, string_view)
453 ::: join(std::initializer_list<T>, string_view)
455 <a id="chrono-api"></a>
456 ## Date and Time Formatting
458 `fmt/chrono.h` provides formatters for
460 - [`std::chrono::duration`](https://en.cppreference.com/w/cpp/chrono/duration)
461 - [`std::chrono::time_point`](
462 https://en.cppreference.com/w/cpp/chrono/time_point)
463 - [`std::tm`](https://en.cppreference.com/w/cpp/chrono/c/tm)
465 The format syntax is described in [Chrono Format Specifications](syntax.md#
466 chrono-format-specifications).
470 #include <fmt/chrono.h>
473 std::time_t t = std::time(nullptr);
475 fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t));
476 // Output: The date is 2020-11-07.
477 // (with 2020-11-07 replaced by the current date)
479 using namespace std::literals::chrono_literals;
481 fmt::print("Default format: {} {}\n", 42s, 100ms);
482 // Output: Default format: 42s 100ms
484 fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s);
485 // Output: strftime-like format: 03:15:30
488 ::: localtime(std::time_t)
490 ::: gmtime(std::time_t)
493 ## Standard Library Types Formatting
495 `fmt/std.h` provides formatters for:
497 - [`std::atomic`](https://en.cppreference.com/w/cpp/atomic/atomic)
498 - [`std::atomic_flag`](https://en.cppreference.com/w/cpp/atomic/atomic_flag)
499 - [`std::bitset`](https://en.cppreference.com/w/cpp/utility/bitset)
500 - [`std::error_code`](https://en.cppreference.com/w/cpp/error/error_code)
501 - [`std::filesystem::path`](https://en.cppreference.com/w/cpp/filesystem/path)
502 - [`std::monostate`](https://en.cppreference.com/w/cpp/utility/variant/monostate)
503 - [`std::optional`](https://en.cppreference.com/w/cpp/utility/optional)
504 - [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location)
505 - [`std::thread::id`](https://en.cppreference.com/w/cpp/thread/thread/id)
506 - [`std::variant`](https://en.cppreference.com/w/cpp/utility/variant/variant)
508 ::: ptr(const std::unique_ptr<T, Deleter>&)
510 ::: ptr(const std::shared_ptr<T>&)
512 ### Formatting Variants
514 A `std::variant` is only formattable if every variant alternative is
515 formattable, and requires the `__cpp_lib_variant` [library
516 feature](https://en.cppreference.com/w/cpp/feature_test).
522 fmt::print("{}", std::variant<char, float>('x'));
523 // Output: variant('x')
525 fmt::print("{}", std::variant<std::monostate, char>());
526 // Output: variant(monostate)
528 <a id="compile-api"></a>
529 ## Format String Compilation
531 `fmt/compile.h` provides format string compilation enabled via the
532 `FMT_COMPILE` macro or the `_cf` user-defined literal defined in
533 namespace `fmt::literals`. Format strings marked with `FMT_COMPILE`
534 or `_cf` are parsed, checked and converted into efficient formatting
535 code at compile-time. This supports arguments of built-in and string
536 types as well as user-defined types with `format` functions taking
537 the format context type as a template parameter in their `formatter`
538 specializations. For example:
540 template <> struct fmt::formatter<point> {
541 constexpr auto parse(format_parse_context& ctx);
543 template <typename FormatContext>
544 auto format(const point& p, FormatContext& ctx) const;
547 Format string compilation can generate more binary code compared to the
548 default API and is only recommended in places where formatting is a
549 performance bottleneck.
555 <a id="color-api"></a>
556 ## Terminal Colors and Text Styles
558 `fmt/color.h` provides support for terminal color and text style output.
560 ::: print(const text_style&, format_string<T...>, T&&...)
562 ::: fg(detail::color_type)
564 ::: bg(detail::color_type)
566 ::: styled(const T&, text_style)
575 <a id="ostream-api"></a>
576 ## `std::ostream` Support
578 `fmt/ostream.h` provides `std::ostream` support including formatting of
579 user-defined types that have an overloaded insertion operator
580 (`operator<<`). In order to make a type formattable via `std::ostream`
581 you should provide a `formatter` specialization inherited from
584 #include <fmt/ostream.h>
587 int year, month, day;
589 friend std::ostream& operator<<(std::ostream& os, const date& d) {
590 return os << d.year << '-' << d.month << '-' << d.day;
594 template <> struct fmt::formatter<date> : ostream_formatter {};
596 std::string s = fmt::format("The date is {}", date{2012, 12, 9});
597 // s == "The date is 2012-12-9"
599 ::: streamed(const T&)
601 ::: print(std::ostream&, format_string<T...>, T&&...)
603 <a id="args-api"></a>
604 ## Dynamic Argument Lists
606 The header `fmt/args.h` provides `dynamic_format_arg_store`, a builder-like API
607 that can be used to construct format argument lists dynamically.
609 ::: dynamic_format_arg_store
611 <a id="printf-api"></a>
614 The header `fmt/printf.h` provides `printf`-like formatting
615 functionality. The following functions use [printf format string
616 syntax](https://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html)
617 with the POSIX extension for positional arguments. Unlike their standard
618 counterparts, the `fmt` functions are type-safe and throw an exception
619 if an argument type doesn't match its format specification.
621 ::: printf(string_view, const T&...)
623 ::: fprintf(std::FILE*, const S&, const T&...)
625 ::: sprintf(const S&, const T&...)
627 <a id="xchar-api"></a>
630 The optional header `fmt/xchar.h` provides support for `wchar_t` and
631 exotic character types.
639 ::: to_wstring(const T&)
641 ## Compatibility with C++20 `std::format`
643 {fmt} implements nearly all of the [C++20 formatting
644 library](https://en.cppreference.com/w/cpp/utility/format) with the
645 following differences:
647 - Names are defined in the `fmt` namespace instead of `std` to avoid
648 collisions with standard library implementations.
649 - Width calculation doesn't use grapheme clusterization. The latter has
650 been implemented in a separate branch but hasn't been integrated yet.