1.. _string-formatting-api: 2 3************* 4API Reference 5************* 6 7All functions and classes provided by the fmt library reside 8in namespace ``fmt`` and macros have prefix ``FMT_``. For brevity the 9namespace is usually omitted in examples. 10 11Format API 12========== 13 14The following functions use :ref:`format string syntax <syntax>` similar 15to the one used by Python's `str.format 16<http://docs.python.org/3/library/stdtypes.html#str.format>`_ function. 17They take *format_str* and *args* as arguments. 18 19*format_str* is a format string that contains literal text and replacement 20fields surrounded by braces ``{}``. The fields are replaced with formatted 21arguments in the resulting string. 22 23*args* is an argument list representing arbitrary arguments. 24 25The `performance of the format API 26<https://github.com/fmtlib/fmt/blob/master/README.rst#speed-tests>`_ is close 27to that of glibc's ``printf`` and better than the performance of IOStreams. 28For even better speed use the `write API`_. 29 30.. _format: 31 32.. doxygenfunction:: format(CStringRef, ArgList) 33 34.. doxygenfunction:: operator""_format(const char *, std::size_t) 35 36.. _print: 37 38.. doxygenfunction:: print(CStringRef, ArgList) 39 40.. doxygenfunction:: print(std::FILE *, CStringRef, ArgList) 41 42.. doxygenclass:: fmt::BasicFormatter 43 :members: 44 45Date and time formatting 46------------------------ 47 48The library supports `strftime 49<http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like date and time 50formatting:: 51 52 #include "fmt/time.h" 53 54 std::time_t t = std::time(nullptr); 55 // Prints "The date is 2016-04-29." (with the current date) 56 fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t)); 57 58The format string syntax is described in the documentation of 59`strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_. 60 61Formatting user-defined types 62----------------------------- 63 64A custom ``format_arg`` function may be implemented and used to format any 65user-defined type. That is how date and time formatting described in the 66previous section is implemented in :file:`fmt/time.h`. The following example 67shows how to implement custom formatting for a user-defined structure. 68 69:: 70 71 struct MyStruct { double a, b; }; 72 73 void format_arg(fmt::BasicFormatter<char> &f, 74 const char *&format_str, const MyStruct &s) { 75 f.writer().write("[MyStruct: a={:.1f}, b={:.2f}]", s.a, s.b); 76 } 77 78 MyStruct m = { 1, 2 }; 79 std::string s = fmt::format("m={}", n); 80 // s == "m=[MyStruct: a=1.0, b=2.00]" 81 82Note in the example above the ``format_arg`` function ignores the contents of 83``format_str`` so the type will always be formatted as specified. See 84``format_arg`` in :file:`fmt/time.h` for an advanced example of how to use 85the ``format_str`` argument to customize the formatted output. 86 87This section shows how to define a custom format function for a user-defined 88type. The next section describes how to get ``fmt`` to use a conventional stream 89output ``operator<<`` when one is defined for a user-defined type. 90 91``std::ostream`` support 92------------------------ 93 94The header ``fmt/ostream.h`` provides ``std::ostream`` support including 95formatting of user-defined types that have overloaded ``operator<<``:: 96 97 #include "fmt/ostream.h" 98 99 class Date { 100 int year_, month_, day_; 101 public: 102 Date(int year, int month, int day): year_(year), month_(month), day_(day) {} 103 104 friend std::ostream &operator<<(std::ostream &os, const Date &d) { 105 return os << d.year_ << '-' << d.month_ << '-' << d.day_; 106 } 107 }; 108 109 std::string s = fmt::format("The date is {}", Date(2012, 12, 9)); 110 // s == "The date is 2012-12-9" 111 112.. doxygenfunction:: print(std::ostream&, CStringRef, ArgList) 113 114Argument formatters 115------------------- 116 117It is possible to change the way arguments are formatted by providing a 118custom argument formatter class:: 119 120 // A custom argument formatter that formats negative integers as unsigned 121 // with the ``x`` format specifier. 122 class CustomArgFormatter : 123 public fmt::BasicArgFormatter<CustomArgFormatter, char> { 124 public: 125 CustomArgFormatter(fmt::BasicFormatter<char, CustomArgFormatter> &f, 126 fmt::FormatSpec &s, const char *fmt) 127 : fmt::BasicArgFormatter<CustomArgFormatter, char>(f, s, fmt) {} 128 129 void visit_int(int value) { 130 if (spec().type() == 'x') 131 visit_uint(value); // convert to unsigned and format 132 else 133 fmt::BasicArgFormatter<CustomArgFormatter, char>::visit_int(value); 134 } 135 }; 136 137 std::string custom_format(const char *format_str, fmt::ArgList args) { 138 fmt::MemoryWriter writer; 139 // Pass custom argument formatter as a template arg to BasicFormatter. 140 fmt::BasicFormatter<char, CustomArgFormatter> formatter(args, writer); 141 formatter.format(format_str); 142 return writer.str(); 143 } 144 FMT_VARIADIC(std::string, custom_format, const char *) 145 146 std::string s = custom_format("{:x}", -42); // s == "ffffffd6" 147 148.. doxygenclass:: fmt::ArgVisitor 149 :members: 150 151.. doxygenclass:: fmt::BasicArgFormatter 152 :members: 153 154.. doxygenclass:: fmt::ArgFormatter 155 :members: 156 157Printf formatting 158----------------- 159 160The header ``fmt/printf.h`` provides ``printf``-like formatting functionality. 161The following functions use `printf format string syntax 162<http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with 163the POSIX extension for positional arguments. Unlike their standard 164counterparts, the ``fmt`` functions are type-safe and throw an exception if an 165argument type doesn't match its format specification. 166 167.. doxygenfunction:: printf(CStringRef, ArgList) 168 169.. doxygenfunction:: fprintf(std::FILE *, CStringRef, ArgList) 170 171.. doxygenfunction:: fprintf(std::ostream&, CStringRef, ArgList) 172 173.. doxygenfunction:: sprintf(CStringRef, ArgList) 174 175.. doxygenclass:: fmt::PrintfFormatter 176 :members: 177 178.. doxygenclass:: fmt::BasicPrintfArgFormatter 179 :members: 180 181.. doxygenclass:: fmt::PrintfArgFormatter 182 :members: 183 184Write API 185========= 186 187The write API provides classes for writing formatted data into character 188streams. It is usually faster than the `format API`_ but, as IOStreams, 189may result in larger compiled code size. The main writer class is 190`~fmt::BasicMemoryWriter` which stores its output in a memory buffer and 191provides direct access to it. It is possible to create custom writers that 192store output elsewhere by subclassing `~fmt::BasicWriter`. 193 194.. doxygenclass:: fmt::BasicWriter 195 :members: 196 197.. doxygenclass:: fmt::BasicMemoryWriter 198 :members: 199 200.. doxygenclass:: fmt::BasicArrayWriter 201 :members: 202 203.. doxygenclass:: fmt::BasicStringWriter 204 :members: 205 206.. doxygenfunction:: bin(int) 207 208.. doxygenfunction:: oct(int) 209 210.. doxygenfunction:: hex(int) 211 212.. doxygenfunction:: hexu(int) 213 214.. doxygenfunction:: pad(int, unsigned, Char) 215 216Utilities 217========= 218 219.. doxygenfunction:: fmt::arg(StringRef, const T&) 220 221.. doxygenfunction:: operator""_a(const char *, std::size_t) 222 223.. doxygendefine:: FMT_CAPTURE 224 225.. doxygendefine:: FMT_VARIADIC 226 227.. doxygenclass:: fmt::ArgList 228 :members: 229 230.. doxygenfunction:: fmt::to_string(const T&) 231 232.. doxygenclass:: fmt::BasicStringRef 233 :members: 234 235.. doxygenclass:: fmt::BasicCStringRef 236 :members: 237 238.. doxygenclass:: fmt::Buffer 239 :protected-members: 240 :members: 241 242System errors 243============= 244 245.. doxygenclass:: fmt::SystemError 246 :members: 247 248.. doxygenfunction:: fmt::format_system_error 249 250.. doxygenclass:: fmt::WindowsError 251 :members: 252 253.. _formatstrings: 254 255Custom allocators 256================= 257 258The fmt library supports custom dynamic memory allocators. 259A custom allocator class can be specified as a template argument to 260:class:`fmt::BasicMemoryWriter`:: 261 262 typedef fmt::BasicMemoryWriter<char, CustomAllocator> CustomMemoryWriter; 263 264It is also possible to write a formatting function that uses a custom 265allocator:: 266 267 typedef std::basic_string<char, std::char_traits<char>, CustomAllocator> 268 CustomString; 269 270 CustomString format(CustomAllocator alloc, fmt::CStringRef format_str, 271 fmt::ArgList args) { 272 CustomMemoryWriter writer(alloc); 273 writer.write(format_str, args); 274 return CustomString(writer.data(), writer.size(), alloc); 275 } 276 FMT_VARIADIC(CustomString, format, CustomAllocator, fmt::CStringRef) 277