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 argument handling 10 facilities and a lightweight subset of formatting functions 11* :ref:`fmt/format.h <format-api>`: the full format API providing compile-time 12 format string checks, wide string, output iterator and user-defined type 13 support 14* :ref:`fmt/ranges.h <ranges-api>`: additional formatting support for ranges 15 and tuples 16* :ref:`fmt/chrono.h <chrono-api>`: date and time formatting 17* :ref:`fmt/compile.h <compile-api>`: format string compilation 18* :ref:`fmt/color.h <color-api>`: terminal color and text style 19* :ref:`fmt/ostream.h <ostream-api>`: ``std::ostream`` support 20* :ref:`fmt/printf.h <printf-api>`: ``printf`` formatting 21 22All functions and types provided by the library reside in namespace ``fmt`` and 23macros have prefix ``FMT_``. 24 25.. _core-api: 26 27Core API 28======== 29 30``fmt/core.h`` defines the core API which provides argument handling facilities 31and a lightweight subset of formatting functions. In the header-only mode 32include ``fmt/format.h`` instead of ``fmt/core.h``. 33 34The following functions use :ref:`format string syntax <syntax>` 35similar to that of Python's `str.format 36<http://docs.python.org/3/library/stdtypes.html#str.format>`_. 37They take *format_str* and *args* as arguments. 38 39*format_str* is a format string that contains literal text and replacement 40fields surrounded by braces ``{}``. The fields are replaced with formatted 41arguments in the resulting string. A function taking *format_str* doesn't 42participate in an overload resolution if the latter is not a string. 43 44*args* is an argument list representing objects to be formatted. 45 46.. _format: 47 48.. doxygenfunction:: format(const S&, Args&&...) 49.. doxygenfunction:: vformat(const S&, basic_format_args<buffer_context<type_identity_t<Char>>>) 50 51.. doxygenfunction:: fmt::format_to(OutputIt, const S&, Args&&...) 52.. doxygenfunction:: fmt::format_to_n(OutputIt, size_t, const S&, const Args&...) 53.. doxygenfunction:: fmt::formatted_size(string_view, Args&&...) 54 55.. _print: 56 57.. doxygenfunction:: print(const S&, Args&&...) 58.. doxygenfunction:: vprint(string_view, format_args) 59 60.. doxygenfunction:: print(std::FILE *, const S&, Args&&...) 61.. doxygenfunction:: vprint(std::FILE *, string_view, format_args) 62 63Named Arguments 64--------------- 65 66.. doxygenfunction:: fmt::arg(const S&, const T&) 67 68Named arguments are not supported in compile-time checks at the moment. 69 70Argument Lists 71-------------- 72 73You can create your own formatting function with compile-time checks and small 74binary footprint, for example (https://godbolt.org/z/oba4Mc): 75 76.. code:: c++ 77 78 #include <fmt/format.h> 79 80 void vlog(const char* file, int line, fmt::string_view format, 81 fmt::format_args args) { 82 fmt::print("{}: {}: ", file, line); 83 fmt::vprint(format, args); 84 } 85 86 template <typename S, typename... Args> 87 void log(const char* file, int line, const S& format, Args&&... args) { 88 vlog(file, line, format, 89 fmt::make_args_checked<Args...>(format, args...)); 90 } 91 92 #define MY_LOG(format, ...) \ 93 log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__) 94 95 MY_LOG("invalid squishiness: {}", 42); 96 97Note that ``vlog`` is not parameterized on argument types which improves compile 98times and reduces binary code size compared to a fully parameterized version. 99 100.. doxygenfunction:: fmt::make_args_checked(const S&, const remove_reference_t<Args>&...) 101 102.. doxygenfunction:: fmt::make_format_args(const Args&...) 103 104.. doxygenclass:: fmt::format_arg_store 105 :members: 106 107.. doxygenclass:: fmt::dynamic_format_arg_store 108 :members: 109 110.. doxygenclass:: fmt::basic_format_args 111 :members: 112 113.. doxygenstruct:: fmt::format_args 114 115.. doxygenclass:: fmt::basic_format_arg 116 :members: 117 118Compatibility 119------------- 120 121.. doxygenclass:: fmt::basic_string_view 122 :members: 123 124.. doxygentypedef:: fmt::string_view 125.. doxygentypedef:: fmt::wstring_view 126 127Locale 128------ 129 130All formatting is locale-independent by default. Use the ``'L'`` format 131specifier to insert the appropriate number separator characters from the 132locale:: 133 134 #include <fmt/core.h> 135 #include <locale> 136 137 std::locale::global(std::locale("en_US.UTF-8")); 138 auto s = fmt::format("{:L}", 1000000); // s == "1,000,000" 139 140.. _format-api: 141 142Format API 143========== 144 145``fmt/format.h`` defines the full format API providing compile-time format 146string checks, wide string, output iterator and user-defined type support. 147 148Compile-time Format String Checks 149--------------------------------- 150 151Compile-time checks are enabled when using ``FMT_STRING``. They support built-in 152and string types as well as user-defined types with ``constexpr`` ``parse`` 153functions in their ``formatter`` specializations. 154 155.. doxygendefine:: FMT_STRING 156 157.. _udt: 158 159Formatting User-defined Types 160----------------------------- 161 162To make a user-defined type formattable, specialize the ``formatter<T>`` struct 163template and implement ``parse`` and ``format`` methods:: 164 165 #include <fmt/format.h> 166 167 struct point { double x, y; }; 168 169 template <> 170 struct fmt::formatter<point> { 171 // Presentation format: 'f' - fixed, 'e' - exponential. 172 char presentation = 'f'; 173 174 // Parses format specifications of the form ['f' | 'e']. 175 constexpr auto parse(format_parse_context& ctx) { 176 // auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) // c++11 177 // [ctx.begin(), ctx.end()) is a character range that contains a part of 178 // the format string starting from the format specifications to be parsed, 179 // e.g. in 180 // 181 // fmt::format("{:f} - point of interest", point{1, 2}); 182 // 183 // the range will contain "f} - point of interest". The formatter should 184 // parse specifiers until '}' or the end of the range. In this example 185 // the formatter should parse the 'f' specifier and return an iterator 186 // pointing to '}'. 187 188 // Parse the presentation format and store it in the formatter: 189 auto it = ctx.begin(), end = ctx.end(); 190 if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++; 191 192 // Check if reached the end of the range: 193 if (it != end && *it != '}') 194 throw format_error("invalid format"); 195 196 // Return an iterator past the end of the parsed range: 197 return it; 198 } 199 200 // Formats the point p using the parsed format specification (presentation) 201 // stored in this formatter. 202 template <typename FormatContext> 203 auto format(const point& p, FormatContext& ctx) { 204 // auto format(const point &p, FormatContext &ctx) -> decltype(ctx.out()) // c++11 205 // ctx.out() is an output iterator to write to. 206 return format_to( 207 ctx.out(), 208 presentation == 'f' ? "({:.1f}, {:.1f})" : "({:.1e}, {:.1e})", 209 p.x, p.y); 210 } 211 }; 212 213Then you can pass objects of type ``point`` to any formatting function:: 214 215 point p = {1, 2}; 216 std::string s = fmt::format("{:f}", p); 217 // s == "(1.0, 2.0)" 218 219You can also reuse existing formatters via inheritance or composition, for 220example:: 221 222 enum class color {red, green, blue}; 223 224 template <> struct fmt::formatter<color>: formatter<string_view> { 225 // parse is inherited from formatter<string_view>. 226 template <typename FormatContext> 227 auto format(color c, FormatContext& ctx) { 228 string_view name = "unknown"; 229 switch (c) { 230 case color::red: name = "red"; break; 231 case color::green: name = "green"; break; 232 case color::blue: name = "blue"; break; 233 } 234 return formatter<string_view>::format(name, ctx); 235 } 236 }; 237 238Since ``parse`` is inherited from ``formatter<string_view>`` it will recognize 239all string format specifications, for example 240 241.. code-block:: c++ 242 243 fmt::format("{:>10}", color::blue) 244 245will return ``" blue"``. 246 247You can also write a formatter for a hierarchy of classes:: 248 249 #include <type_traits> 250 #include <fmt/format.h> 251 252 struct A { 253 virtual ~A() {} 254 virtual std::string name() const { return "A"; } 255 }; 256 257 struct B : A { 258 virtual std::string name() const { return "B"; } 259 }; 260 261 template <typename T> 262 struct fmt::formatter<T, std::enable_if_t<std::is_base_of<A, T>::value, char>> : 263 fmt::formatter<std::string> { 264 template <typename FormatCtx> 265 auto format(const A& a, FormatCtx& ctx) { 266 return fmt::formatter<std::string>::format(a.name(), ctx); 267 } 268 }; 269 270 int main() { 271 B b; 272 A& a = b; 273 fmt::print("{}", a); // prints "B" 274 } 275 276If a type provides both a ``formatter`` specialization and an implicit 277conversion to a formattable type, the specialization takes precedence over the 278conversion. 279 280.. doxygenclass:: fmt::basic_format_parse_context 281 :members: 282 283Output Iterator Support 284----------------------- 285 286.. doxygenfunction:: fmt::format_to(OutputIt, const S&, Args&&...) 287.. doxygenfunction:: fmt::format_to_n(OutputIt, size_t, const S&, const Args&...) 288.. doxygenstruct:: fmt::format_to_n_result 289 :members: 290 291Literal-based API 292----------------- 293 294The following user-defined literals are defined in ``fmt/format.h``. 295 296.. doxygenfunction:: operator""_format(const char *, size_t) 297 298.. doxygenfunction:: operator""_a(const char *, size_t) 299 300Utilities 301--------- 302 303.. doxygenstruct:: fmt::is_char 304 305.. doxygentypedef:: fmt::char_t 306 307.. doxygenfunction:: fmt::ptr(const T *) 308.. doxygenfunction:: fmt::ptr(const std::unique_ptr<T>&) 309.. doxygenfunction:: fmt::ptr(const std::shared_ptr<T>&) 310 311.. doxygenfunction:: fmt::to_string(const T&) 312 313.. doxygenfunction:: fmt::to_wstring(const T&) 314 315.. doxygenfunction:: fmt::to_string_view(const Char *) 316 317.. doxygenfunction:: fmt::join(Range&&, string_view) 318 319.. doxygenfunction:: fmt::join(It, Sentinel, string_view) 320 321.. doxygenclass:: fmt::detail::buffer 322 :members: 323 324.. doxygenclass:: fmt::basic_memory_buffer 325 :protected-members: 326 :members: 327 328System Errors 329------------- 330 331fmt does not use ``errno`` to communicate errors to the user, but it may call 332system functions which set ``errno``. Users should not make any assumptions about 333the value of ``errno`` being preserved by library functions. 334 335.. doxygenclass:: fmt::system_error 336 :members: 337 338.. doxygenfunction:: fmt::format_system_error 339 340.. doxygenclass:: fmt::windows_error 341 :members: 342 343Custom Allocators 344----------------- 345 346The {fmt} library supports custom dynamic memory allocators. 347A custom allocator class can be specified as a template argument to 348:class:`fmt::basic_memory_buffer`:: 349 350 using custom_memory_buffer = 351 fmt::basic_memory_buffer<char, fmt::inline_buffer_size, custom_allocator>; 352 353It is also possible to write a formatting function that uses a custom 354allocator:: 355 356 using custom_string = 357 std::basic_string<char, std::char_traits<char>, custom_allocator>; 358 359 custom_string vformat(custom_allocator alloc, fmt::string_view format_str, 360 fmt::format_args args) { 361 custom_memory_buffer buf(alloc); 362 fmt::vformat_to(buf, format_str, args); 363 return custom_string(buf.data(), buf.size(), alloc); 364 } 365 366 template <typename ...Args> 367 inline custom_string format(custom_allocator alloc, 368 fmt::string_view format_str, 369 const Args& ... args) { 370 return vformat(alloc, format_str, fmt::make_format_args(args...)); 371 } 372 373The allocator will be used for the output container only. Formatting functions 374normally don't do any allocations for built-in and string types except for 375non-default floating-point formatting that occasionally falls back on 376``sprintf``. 377 378.. _ranges-api: 379 380Ranges and Tuple Formatting 381=========================== 382 383The library also supports convenient formatting of ranges and tuples:: 384 385 #include <fmt/ranges.h> 386 387 std::tuple<char, int, float> t{'a', 1, 2.0f}; 388 // Prints "('a', 1, 2.0)" 389 fmt::print("{}", t); 390 391 392NOTE: currently, the overload of ``fmt::join`` for iterables exists in the main 393``format.h`` header, but expect this to change in the future. 394 395Using ``fmt::join``, you can separate tuple elements with a custom separator:: 396 397 #include <fmt/ranges.h> 398 399 std::tuple<int, char> t = {1, 'a'}; 400 // Prints "1, a" 401 fmt::print("{}", fmt::join(t, ", ")); 402 403.. _chrono-api: 404 405Date and Time Formatting 406======================== 407 408The library supports `strftime 409<http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like date and time 410formatting:: 411 412 #include <fmt/chrono.h> 413 414 std::time_t t = std::time(nullptr); 415 // Prints "The date is 2016-04-29." (with the current date) 416 fmt::print("The date is {:%Y-%m-%d}.", fmt::localtime(t)); 417 418The format string syntax is described in the documentation of 419`strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_. 420 421.. _compile-api: 422 423Format string compilation 424========================= 425 426``fmt/compile.h`` provides format string compilation support when using 427``FMT_COMPILE``. Format strings are parsed, checked and converted 428into efficient formatting code at compile-time. 429This supports arguments of built-in and string types as well as user-defined types 430with ``constexpr`` ``parse`` functions in their ``formatter`` specializations. 431Format string compilation can generate more binary code compared to the default 432API and is only recommended in places where formatting is a performance 433bottleneck. 434 435.. doxygendefine:: FMT_COMPILE 436 437.. _color-api: 438 439Terminal color and text style 440============================= 441 442``fmt/color.h`` provides support for terminal color and text style output. 443 444.. doxygenfunction:: print(const text_style&, const S&, const Args&...) 445 446.. _ostream-api: 447 448``std::ostream`` Support 449======================== 450 451``fmt/ostream.h`` provides ``std::ostream`` support including formatting of 452user-defined types that have overloaded ``operator<<``:: 453 454 #include <fmt/ostream.h> 455 456 class date { 457 int year_, month_, day_; 458 public: 459 date(int year, int month, int day): year_(year), month_(month), day_(day) {} 460 461 friend std::ostream& operator<<(std::ostream& os, const date& d) { 462 return os << d.year_ << '-' << d.month_ << '-' << d.day_; 463 } 464 }; 465 466 std::string s = fmt::format("The date is {}", date(2012, 12, 9)); 467 // s == "The date is 2012-12-9" 468 469.. doxygenfunction:: print(std::basic_ostream<Char>&, const S&, Args&&...) 470 471.. _printf-api: 472 473``printf`` Formatting 474===================== 475 476The header ``fmt/printf.h`` provides ``printf``-like formatting functionality. 477The following functions use `printf format string syntax 478<http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with 479the POSIX extension for positional arguments. Unlike their standard 480counterparts, the ``fmt`` functions are type-safe and throw an exception if an 481argument type doesn't match its format specification. 482 483.. doxygenfunction:: printf(const S&, const Args&...) 484 485.. doxygenfunction:: fprintf(std::FILE *, const S&, const Args&...) 486 487.. doxygenfunction:: fprintf(std::basic_ostream<Char>&, const S&, const Args&...) 488 489.. doxygenfunction:: sprintf(const S&, const Args&...) 490 491Compatibility with C++20 ``std::format`` 492======================================== 493 494{fmt} implements nearly all of the `C++20 formatting library 495<https://en.cppreference.com/w/cpp/utility/format>`_ with the following 496differences: 497 498* Names are defined in the ``fmt`` namespace instead of ``std`` to avoid 499 collisions with standard library implementations. 500* The ``'L'`` format specifier cannot be combined with presentation specifiers 501 yet. 502* Width calculation doesn't use grapheme clusterization. The latter has been 503 implemented in a separate branch but hasn't been integrated yet. 504* Chrono formatting doesn't support C++20 date types since they are not provided 505 by standard library implementations. 506