Home | History | Annotate | Download | only in doc
      1 .. _string-formatting-api:
      2 
      3 *************
      4 API Reference
      5 *************
      6 
      7 All functions and classes provided by the fmt library reside
      8 in namespace ``fmt`` and macros have prefix ``FMT_``. For brevity the
      9 namespace is usually omitted in examples.
     10 
     11 Format API
     12 ==========
     13 
     14 The following functions use :ref:`format string syntax <syntax>` similar
     15 to the one used by Python's `str.format
     16 <http://docs.python.org/3/library/stdtypes.html#str.format>`_ function.
     17 They take *format_str* and *args* as arguments.
     18 
     19 *format_str* is a format string that contains literal text and replacement
     20 fields surrounded by braces ``{}``. The fields are replaced with formatted
     21 arguments in the resulting string.
     22 
     23 *args* is an argument list representing arbitrary arguments.
     24 
     25 The `performance of the format API
     26 <https://github.com/fmtlib/fmt/blob/master/README.rst#speed-tests>`_ is close
     27 to that of glibc's ``printf`` and better than the performance of IOStreams.
     28 For 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 
     45 Date and time formatting
     46 ------------------------
     47 
     48 The library supports `strftime
     49 <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_-like date and time
     50 formatting::
     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 
     58 The format string syntax is described in the documentation of
     59 `strftime <http://en.cppreference.com/w/cpp/chrono/c/strftime>`_.
     60 
     61 Formatting user-defined types
     62 -----------------------------
     63 
     64 A custom ``format_arg`` function may be implemented and used to format any
     65 user-defined type. That is how date and time formatting described in the
     66 previous section is implemented in :file:`fmt/time.h`. The following example
     67 shows 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 
     82 Note 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
     85 the ``format_str`` argument to customize the formatted output.
     86 
     87 This section shows how to define a custom format function for a user-defined
     88 type. The next section describes how to get ``fmt`` to use a conventional stream
     89 output ``operator<<`` when one is defined for a user-defined type.
     90 
     91 ``std::ostream`` support
     92 ------------------------
     93 
     94 The header ``fmt/ostream.h`` provides ``std::ostream`` support including
     95 formatting 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 
    114 Argument formatters
    115 -------------------
    116 
    117 It is possible to change the way arguments are formatted by providing a
    118 custom 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 
    157 Printf formatting
    158 -----------------
    159 
    160 The header ``fmt/printf.h`` provides ``printf``-like formatting functionality.
    161 The following functions use `printf format string syntax
    162 <http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html>`_ with
    163 the POSIX extension for positional arguments. Unlike their standard
    164 counterparts, the ``fmt`` functions are type-safe and throw an exception if an
    165 argument 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 
    184 Write API
    185 =========
    186 
    187 The write API provides classes for writing formatted data into character
    188 streams. It is usually faster than the `format API`_ but, as IOStreams,
    189 may result in larger compiled code size. The main writer class is
    190 `~fmt::BasicMemoryWriter` which stores its output in a memory buffer and
    191 provides direct access to it. It is possible to create custom writers that
    192 store 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 
    216 Utilities
    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 
    242 System 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 
    255 Custom allocators
    256 =================
    257 
    258 The fmt library supports custom dynamic memory allocators.
    259 A custom allocator class can be specified as a template argument to
    260 :class:`fmt::BasicMemoryWriter`::
    261 
    262     typedef fmt::BasicMemoryWriter<char, CustomAllocator> CustomMemoryWriter;
    263 
    264 It is also possible to write a formatting function that uses a custom
    265 allocator::
    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