<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Text Formatting</title>

<style type="text/css">

body { color: #000000; background-color: #FFFFFF; }
del { text-decoration: line-through; color: #8B0040; }
ins { text-decoration: underline; color: #005100; }

.codeblock { margin-left: 1.2em; }

p.example { margin-left: 1.2em; }
pre.example { margin-left: 1.2em; }
div.example { margin-left: 1.2em; }

code.extract { background-color: #F5F6A2; }
pre.extract { margin-left: 2em; background-color: #F5F6A2;
  border: 1px solid #E1E28E; }

p.function { }
.attribute { margin-left: 2em; }
.attribute dt { float: left; font-style: italic;
  padding-right: 1ex; }
.attribute dd { margin-left: 0em; }

blockquote.std { color: #000000; background-color: #F1F1F1;
  border: 1px solid #D1D1D1;
  padding-left: 0.5em; padding-right: 0.5em; }
blockquote.stddel { text-decoration: line-through;
  color: #000000; background-color: #FFEBFF;
  border: 1px solid #ECD7EC;
  padding-left: 0.5empadding-right: 0.5em; ; }

blockquote.stdins { text-decoration: underline;
  color: #000000; background-color: #C8FFC8;
  border: 1px solid #B3EBB3; padding: 0.5em; }

table { border: 1px solid black; border-spacing: 0px;
  margin-left: auto; margin-right: auto; }
th { text-align: left; vertical-align: top;
  padding-left: 0.8em; border: none; }
td { text-align: left; vertical-align: top;
  padding-left: 0.8em; border: none; }

.content {
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

ul.itemize {
      list-style-type: none;
}

ul.itemize > li{
    margin-top: 0.6em;
    margin-bottom: 0.6em;
}

ul.itemize > li:before {
    content: "\2014";
    position: absolute;
    margin-left: -1.5em;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
        type="text/javascript"> </script>

<script type="text/javascript">$(function() {
    var next_id = 0
    function find_id(node) {
        // Look down the first children of 'node' until we find one
        // with an id. If we don't find one, give 'node' an id and
        // return that.
        var cur = node[0];
        while (cur) {
            if (cur.id) return curid;
            if (cur.tagName == 'A' && cur.name)
                return cur.name;
            cur = cur.firstChild;
        };
        // No id.
        node.attr('id', 'gensection-' + next_id++);
        return node.attr('id');
    };

    // Put a table of contents in the #toc nav.

    // This is a list of <ol> elements, where toc[N] is the list for
    // the current sequence of <h(N+2)> tags. When a header of an
    // existing level is encountered, all higher levels are popped,
    // and an <li> is appended to the level
    var toc = [$("<ol/>")];
    $(':header').not('h1').each(function() {
        var header = $(this);
        // For each <hN> tag, add a link to the toc at the appropriate
        // level.  When toc is one element too short, start a new list
        var levels = {H2: 0, H3: 1, H4: 2, H5: 3, H6: 4};
        var level = levels[this.tagName];
        if (typeof level == 'undefined') {
            throw 'Unexpected tag: ' + this.tagName;
        }
        // Truncate to the new level.
        toc.splice(level + 1, toc.length);
        if (toc.length < level) {
            // Omit TOC entries for skipped header levels.
            return;
        }
        if (toc.length == level) {
            // Add a <ol> to the previous level's last <li> and push
            // it into the array.
            var ol = $('<ol/>')
            toc[toc.length - 1].children().last().append(ol);
            toc.push(ol);
        }
        var header_text = header.text();
        toc[toc.length - 1].append(
            $('<li/>').append($('<a href="#' + find_id(header) + '"/>')
                              .text(header_text)));
    });
    $('#toc').append(toc[0]);
})
</script>

</head>
<body>

<address align=right>
Document number: P0645R4<br>
Audience: Library Evolution, Library<br>
Author: <a href="mailto:victor.zverovich@gmail.com">Victor Zverovich</a><br>
<br>
2018-11-25
</address>
<hr>

<div class="content">
<h1>Text Formatting</h1>

<div id="toc"></div>

<h2><a name="History">Revision History</a></h2>

<h3>Changes since
<a
  href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0645r3.html">R3</a></h2>
<p>
<ul>
<li>Use <code>OutputIterator</code> concept in formatting functions that take
    output iterators and replace the <code>Size</code> template parameter with
    <code>iter_difference_t</code>.
<li>Rename <code>*parse_context</code> to <code>*format_parse_context</code>.
<li>Disallow consecutive zeros in <code>arg-id</code> and <code>width</code>.
<li>Specify formatting of arithmetic and pointer types in terms of
    <code>to_chars</code>.
<li>Clarify what is the current locale.
<li>Use the shortest round-trip format as the default floating-point formatting.
<li>Add missing specializations of <code>formatter</code>.
<li>Clarify that the <code>sign</code> option applies to floating-point infinity
    and NaN.
<li>Propose adding a new entry <code>&lt;format&gt;</code> to table 18 in
    section 15.5.1.2 [headers].
<li>Add section numbers in Proposed wording.
<li>Add a feature test macro.
<li>Remove tautological Ensures clauses.
<li>Merge two <code>make_format_args</code> overloads.
<li>Replace <code>args()</code> with <code>arg(size_t)</code> in
    <code>basic_format_context</code>.
<li>Make <code>format_arg_store</code> exposition-only.
</ul>
</p>

<h3>Changes since
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0645r2.html">R2</a></h2>
<p>
<ul>
<li>Add section <a href="#Visitation">Argument visitation</a> with an example of
how to use the visitation API to implement dynamic format specifiers.
<li>Rename <code>visit</code> to <code>visit_format_arg</code> to distinguish
    from <code>variant</code>'s <code>visit</code>.
<li>Merge [format.syntax] into [format.functions].
<li>Remove the restriction that <code>'\0'</code> cannot be used as a fill
    character.
<li>Replace Postconditions with Ensures.
</ul>
</p>

<h3>Changes since
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0645r1.html">R1</a></h2>

<p>
<ul>
<li>Add the <code>format_to_n</code> function taking an output iterator and a
size.
<li>Add a note that compile-time processing of format strings applies to
user-defined types with custom parsers to section
<a href="#CompileTimeFormat">Compile-time processing of format strings</a>.
<li>Rename <code>count</code> to <code>formatted_size</code>.
<li>Drop nested namespace <code>fmt</code>.
<li>Add <code>format</code> prefix or infix to class and function names to
avoid potential name collision after removing the nested namespace.
<li>Improve wording.
<li>Replace the requirement of implementing a formatter via ostream insertion
operator if the latter is provided with a note that it can be implemented in
such way.
<li>Expand the Acknowledgements section and remove "Reply to".
</ul>
</p>

<h3>Changes since
<a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0645r0.html">R0</a></h2>

<p>
<ul>
<li>Add section <a href="#CompileTimeFormat">Compile-time processing of format
    strings</a>.
<li>Separate parsing and formatting in the extension API replacing
    <code>format_value</code> function template with class template
    <code>formatter</code> to allow compile-time processing of format strings.
<li>Change return type of <code>format_to</code> and <code>vformat_to</code>
    to <code>OutputIterator</code> in synopsis.
<li>Remove sections Null-terminated string view and Format string, and
    replace <code>basic_cstring_view</code> with <code>basic_string_view</code>.
<li>Add a link to the implementation in
    <a href="#Introduction">Introduction</a>.
<li>Add a note regarding time formatting and compatibility with D0355 "Extending
    &lt;chrono&gt; to Calendars and Time Zones" <a href="#16">[16]</a> to
    section <a href="#Extensibility">Extensibility</a>.
<li>Rename <code>basic_args</code> to <code>basic_format_args</code>.
<li>Rename <code>is_numeric</code> to <code>is_arithmetic</code>.
<li>Add the <code>count</code> function that counts the number of characters
    and use it to define output ranges.
<li>Remove <code>basic_buffer</code> and section Formatting buffer and replace
    buffers with output iterators.
<li>Add <a href="#Benchmarks">Appendix A: Benchmarks</a>.
<li>Explain the purpose of the type-erased API in more details in the
    <a href="#Footprint">Binary footprint</a> section.
<li>Add <a href="#BinaryCode">Appendix B: Binary code comparison</a>.
<li>Add formatting function overloads for <code>wchar_t</code> strings.
</ul>
</p>

<h2><a name="Introduction">Introduction</a></h2>

<p>
Even with proliferation of graphical and voice user interfaces, text remains one
of the main ways for humans to interact with computer programs and programming
languages provide a variety of methods to perform text formatting.
The first thing we do when learning a new programming language is often write
a &quot;Hello, World!&quot; program that performs simple formatted output.
</p>

<p>
C++ has not one but two standard APIs for producing formatted output, the
<code>printf</code> family of functions inherited from C and the I/O streams
library (iostreams).
While iostreams are usually the recommended way of producing formatted
output in C++ for safety and extensibility reasons, <code>printf</code> offers
some advantages, such as an arguably more natural function call API, the
separation of formatted message and arguments, possibly with argument reordering
as a POSIX extension, and often more compact source and binary code.
</p>

<p>
This paper proposes a new text formatting library that can be used as a
safe and extensible alternative to the <code>printf</code> family of functions.
It is intended to complement the existing C++ I/O streams library and reuse
some of its infrastructure such as overloaded insertion operators for
user-defined types.
</p>

<p>
Example:

<pre class="example">
<code>string message = format("The answer is {}.", 42);</code>
</pre>
</p>

A full implementation of this proposal is available at
<a href="https://github.com/fmtlib/fmt/tree/std">https://github.com/fmtlib/fmt/tree/std</a>.

<h2><a name="Design">Design</a></h2>

<h3><a name="Syntax">Format string syntax</a></h3>

<p>
Variations of the <code>printf</code> format string syntax are arguably the most
popular among the programming languages and C++ itself inherits <code>printf</code>
from C <a href="#1">[1]</a>. The advantage of the <code>printf</code> syntax is
that many programmers are familiar with it. However, in its current form it has
a number of issues:
</p>

<ul>
<li>Many format specifiers like <code>hh</code>, <code>h</code>, <code>l</code>,
    <code>j</code>, etc. are used only to convey type information.
    They are redundant in type-safe formatting and would unnecessarily
    complicate specification and parsing.</li>
<li>There is no standard way to extend the syntax for user-defined types.</li>
<li>There are subtle differences between different implementations. For example,
    POSIX positional arguments <a href="#2">[2]</a> are not supported on
    some systems <a href="#6">[6]</a>.</li>
<li>Using <code>'%'</code> in a custom format specifier poses difficulties, e.g.
for <code>put_time</code>-like time formatting.</li>
</ul>

<p>
Although it is possible to address these issues while maintaining resemblance
to the original <code>printf</code> format, this will still break compatibility
and can potentially be more confusing to users than introducing a different
syntax.
</p>

<p>
Therefore we propose a new syntax based on the ones used in Python
<a href="#3">[3]</a>, the .NET family of languages <a href="#4">[4]</a>,
and Rust <a href="#5">[5]</a>. This syntax employs <code>'{'</code> and
<code>'}'</code> as replacement field delimiters instead of <code>'%'</code>
and it is described in detail in
<a href="#format.functions">[format.functions]</a>. Some advantages of the
proposal are:
</p>

<ul>
<li>A consistent and easy to parse mini-language focused on formatting rather
    than conveying type information</li>
<li>Extensibility and support for custom format strings for user-defined
    types</li>
<li>Positional arguments</li>
<li>Support for both locale-specific and locale-independent formatting (see
    <a href="#Locale">Locale support</a>)</li>
<li>Formatting improvements such as better alignment control, fill character,
    and binary representation</li>
</ul>

<p>
The syntax is expressive enough to enable translation, possibly automated,
of most <code>printf</code> format strings. The correspondence between
<code>printf</code> and the new syntax is given in the following table:
</p>

<table>
<thead>
<tr><th>printf</th><th>new</th></tr>
</thead>
<tbody>
<tr><td>-</td><td>&lt;</td></tr>
<tr><td>+</td><td>+</td></tr>
<tr><td><em>space</em></td><td><em>space</em></td></tr>
<tr><td>#</td><td>#</td></tr>
<tr><td>0</td><td>0</td></tr>
<tr><td>hh</td><td>unused</td></tr>
<tr><td>h</td><td>unused</td></tr>
<tr><td>l</td><td>unused</td></tr>
<tr><td>ll</td><td>unused</td></tr>
<tr><td>j</td><td>unused</td></tr>
<tr><td>z</td><td>unused</td></tr>
<tr><td>t</td><td>unused</td></tr>
<tr><td>L</td><td>unused</td></tr>
<tr><td>c</td><td>c (optional)</td></tr>
<tr><td>s</td><td>s (optional)</td></tr>
<tr><td>d</td><td>d (optional)</td></tr>
<tr><td>i</td><td>d (optional)</td></tr>
<tr><td>o</td><td>o</td></tr>
<tr><td>x</td><td>x</td></tr>
<tr><td>X</td><td>X</td></tr>
<tr><td>u</td><td>d (optional)</td></tr>
<tr><td>f</td><td>f</td></tr>
<tr><td>F</td><td>F</td></tr>
<tr><td>e</td><td>e</td></tr>
<tr><td>E</td><td>E</td></tr>
<tr><td>a</td><td>a</td></tr>
<tr><td>A</td><td>A</td></tr>
<tr><td>g</td><td>g (optional)</td></tr>
<tr><td>G</td><td>G</td></tr>
<tr><td>n</td><td>unused</td></tr>
<tr><td>p</td><td>p (optional)</td></tr>
</tbody>
</table>

<p>
Width and precision are represented similarly in <code>printf</code> and the
proposed syntax with the only difference that runtime value is specified by
<code>'*'</code> in the former and <code>'{}'</code> in the latter, possibly
with the index of the argument inside the braces:
</p>

<pre class="example">
<code>printf("%*s", 10, "foo");
format("{:{}}", "foo", 10);</code>
</pre>

<p>
As can be seen from the table above, most of the specifiers remain the same
which simplifies migration from <code>printf</code>. A notable difference is
in the alignment specification. The proposed syntax allows left, center,
and right alignment represented by <code>'&lt;'</code>, <code>'^'</code>,
and <code>'&gt;'</code> respectively which is more expressive than the
corresponding <code>printf</code> syntax. The latter only supports left and
right alignment.
</p>

<p>
The following example uses center alignment and <code>'*'</code> as a fill
character:
</p>

<pre class="example">
<code>format("{:*^30}", "centered");</code>
</pre>

<p>
resulting in <code>"***********centered***********"</code>.
The same formatting cannot be easily achieved with <code>printf</code>.
</p>

<p>
In addition to positional arguments, the grammar can be easily extended to
support named arguments.
</p>

<h3><a name="Extensibility">Extensibility</a></h3>

<p>
Both the format string syntax and the API are designed with extensibility in
mind. The mini-language can be extended for user-defined types and users can
provide functions that implement parsing, possibly at compile time, and
formatting for such types.
</p>

<p>The general syntax of a replacement field in a format string is

<pre class="example">
<code>replacement-field ::= '{' [arg-id] [':' format-spec] '}'</code>
</pre>

<p>
where <code>format-spec</code> is predefined for built-in types, but can be
customized for user-defined types. For example, the syntax can be extended
for <code>put_time</code>-like date and time formatting
</p>

<pre class="example">
<code>time_t t = time(nullptr);
string date = format("The date is {0:%Y-%m-%d}.", *localtime(&amp;t));
</code></pre>

<p>by providing a specialization of <code>formatter</code> for <code>tm</code>:
</p>

<pre class="example">
<code>template&lt;&gt;
  struct formatter&lt;tm&gt; {
    constexpr format_parse_context::iterator parse(format_parse_context&amp; ctx);

    template&lt;class FormatContext&gt;
      typename FormatContext::iterator format(const tm&amp; tm, FormatContext&amp; ctx);
  };
</code></pre>

<p>
The <code>formatter&lt;tm&gt;::parse</code> function parses the
<code>format-spec</code> portion of the format string corresponding to the
current argument and <code>formatter&lt;tm&gt;::format</code> formats the value
and writes the output via the iterator <code>ctx.begin()</code>.
</p>

<p>
Note that date and time formatting is not covered by this proposal but
formatting facilities provided by D0355 "Extending &lt;chrono&gt; to Calendars
and Time Zones" <a href="#16">[16]</a> can be easily implemented using this
extension API.
</p>

<p>
An implementation of <code>formatter&lt;T&gt;::format</code> can use ostream
insertion <code>operator&lt;&lt;</code> for user-defined type <code>T</code> if
available.
</p>

<!-- ADL-based API: https://godbolt.org/g/p1wQPr -->
<p>
The extension API is based on specialization instead of the argument-dependent
lookup (ADL), because the <code>parse</code> function doesn't take the object to
be formatted as an argument and therefore some other way of parameterizing it on
the argument type <code>T</code> such as introducing a dummy argument has to be
used, e.g.
<pre class="example">
<code>constexpr auto parse(type&lt;T&gt;, format_parse_context&amp; ctx);
</code></pre>
</p>

<p>
Another problem with ADL-based approach is compile-time performance as pointed
out in <a href="#20">[20]</a>:

<blockquote>
Overload resolution on <code>operator&lt;&lt;</code> tends to get expensive for larger projects
with hundreds or thousands of candidates in the overload set. This seems hard to
resolve, since choosing a different name for <code>operator&lt;&lt;</code> simply shifts the expense
of overload resolution to a differently-named function.
</blockquote>
</p>

<h3><a name="Safety">Safety</a></h3>

<p>
Formatting functions rely on variadic templates instead of the mechanism
provided by <code>&lt;cstdarg&gt;</code>. The type information is captured
automatically and passed to formatters guaranteeing type safety and making
many of the <code>printf</code> specifiers redundant (see <a href="#Syntax">
Format String Syntax</a>). Memory management is automatic to prevent
buffer overflow errors common to <code>printf</code>.
</p>

<h3><a name="Locale">Locale support</a></h3>

<p>
As pointed out in P0067 "Elementary string conversions"<a href="#17">[17]</a>
there is a number of use cases that do not require internationalization support,
but do require high throughput when produced by a server. These include various
text-based interchange formats such as JSON or XML. The need for
locale-independent functions for conversions between integers and strings and
between floating-point numbers and strings has also been highlighted in
<a href="#20">[20]</a>. Therefore a user should be able to
easily control whether to use locales or not during formatting.
</p>

<p>
We follow Python's approach <a href="#3">[3]</a> and designate a separate format
specifier <code>'n'</code> for locale-aware numeric formatting. It applies to
all integral and floating-point types. All other specifiers produce output
unaffected by locale settings. This can also have positive effect on performance
because locale-independent formatting can be implemented more efficiently.
</p>

<h3><a name="PosArguments">Positional arguments</a></h3>

<p>
An important feature for localization is the ability to rearrange formatting
arguments as the word order may vary in different languages
<a href="#7">[7]</a>. For example:
</p>

<pre class="example">
<code>printf("String `%s' has %d characters\n", string, length(string)));</code>
</pre>

<p>A possible German translation of the format string might be:</p>

<pre class="example">
<code>"%2$d Zeichen lang ist die Zeichenkette `%1$s'\n"</code>
</pre>

<p>
using POSIX positional arguments <a href="#2">[2]</a>. Unfortunately these
positional specifiers are not portable <a href="#6">[6]</a>. The C++ I/O
streams don't support such rearranging of arguments by design because they
are interleaved with the portions of the literal string:
</p>

<pre class="example">
<code>cout << "String `" << string << "' has " << length(string) << " characters\n";</code>
</pre>

<p>
The current proposal allows both positional and automatically numbered
arguments, for example:
</p>

<pre class="example">
<code>format("String `{}' has {} characters\n", string, length(string)));</code>
</pre>

<p>with the German translation of the format string being:</p>

<pre class="example">
<code>"{1} Zeichen lang ist die Zeichenkette `{0}'\n"</code>
</pre>

<h3><a name="Performance">Performance</a></h3>

<p>
The formatting library has been designed with performance in mind. It tries to
minimize the number of virtual function calls and dynamic memory allocations
done per formatting operation. In particular, if formatting output can fit
into a fixed-size array allocated on stack, it should be possible to avoid
both of them altogether by using a suitable API.
</p>

<p>
The <code>format_to</code> function takes an arbitrary output iterator and, for
performance reasons, can be specialized for random-access and contiguous
iterators as shown in the reference implementation <a href="#14">[14]</a>.
</p>

<p>
The locale-independent formatting can also be implemented more efficiently than
the locale-aware one. However, the main goal for the former is to support
specific use cases (see <a href="Locale">Locale support</a>) rather than to
improve performance.
</p>

<p>
See <a href="#Benchmarks">Appendix A: Benchmarks</a> for a small performance
comparison of the reference implementation of this proposal versus the standard
formatting facilities.
</p>

<h3><a name="Footprint">Binary footprint</a></h3>

<p>
In order to minimize binary code size each formatting function that uses
variadic templates can be implemented as a small inline wrapper around its
non-variadic counterpart. This wrapper creates a <code>basic_format_args</code>
object, representing an array of type-erased argument references, with
<code>make_format_args</code> and calls the non-variadic function to do the actual
work. For example, the <code>format</code> variadic function calls
<code>vformat</code>:
</p>

<pre><code>string vformat(string_view fmt, format_args args);

template&lt;class... Args&gt;
  inline string format(string_view fmt, const Args&amp;... args) {
    return vformat(fmt, make_format_args(args...));
  }</code></pre>

<p>
<code>basic_format_args</code> can be implemented as an array of tagged unions.
If the number of arguments is small then the tags that indicate the arguments
types can be combined and passed into a formatting function as a single integer.
This single integer representing all argument types is computed at compile time
and only needs to be stored, resulting in smaller binary code.
</p>

<p>
Given a reasonable optimizing compiler, this will result in a compact per-call
binary code, effectively consisting of placing argument pointers (or, possibly,
copies for primitive types) and packed tags on the stack and calling a
formatting function. See <a href="#BinaryCode">Appendix B: Binary code comparison</a>
for a specific example.
</p>

<p>
Exposing the type-erased API rather than making it an implementation detail and
only providing variadic functions allows applying the same technique to the
user code. For example, consider a simple logging function that writes a
formatted error message to <code>clog</code>:
<p>

<pre><code>template&lt;class... Args&gt;
  void log_error(int code, string_view fmt, const Args&amp;... args) {
    clog &lt;&lt; "Error " &lt;&lt; code &lt;&lt; ": " &lt;&lt; format(fmt, args...);
  }</code></pre>

<p>
The code for this function will be generated for every combination of argument
types which can be undesirable. However, if we use the type-erased API, there
will be only one instance of the logging function while the wrapper function
can be trivially inlined:
</p>

<pre><code>void vlog_error(int code, string_view fmt, format_args args) {
  clog &lt;&lt; "Error " &lt;&lt; code &lt;&lt; ": " &lt;&lt; vformat(fmt, args);
}

template&lt;class... Args&gt;
  inline void log_error(int code, string_view fmt, const Args&amp;... args) {
    vlog_error(code, fmt, make_format_args(args...));
  }</code></pre>

<p>
The current design allows users to easily switch between the two approaches.
</p>

<p>
For similar reasons formatting functions take format strings as instances of
<code>basic_string_view</code> instead of being parameterized on a string type.
This allows implicit conversions from null-terminated character strings and
<code>basic_string</code> without affecting code size.
</p>

<h3><a name="Traits">Format strings and <code>char_traits</code></a></h3>

<p>
Format strings intentionally use the default character traits in the formatting
functions API because making traits customizable creates potential problems with
handling format specifications.
</p>

<p>
Consider the following example:

<pre>
<code>using ci_string_view = std::basic_string_view&lt;char, ci_char_traits&gt;;
auto s = format(ci_string_view("{:X}"), 0xCAFE);</code></pre>

where <code>ci_char_traits</code> is a character trait with case-insensitive
comparison.
</p>

<p>
Since the format specification grammar is case-sensitive, the behavior of such
code is no longer intuitive. There are several options:

<ol>
<li>ill-formed (current proposal),
<li>well-formed and <code>s == "cafe"</code>,
<li>well-formed and <code>s == "CAFE"</code>.
</ol>
</p>

<p>Option 2 is a potential pessimization because comparisons will have to go
through traits while option 3 effectively ignores traits.</p>

<p>Existing standard functions that take format strings (<code>printf</code>,
<code>put_time</code>, <code>strftime</code>) do not allow passing character
traits.
</p>

<h3><a name="CompileTimeFormat">Compile-time processing of format strings</a>
</h3>

<p>It is possible to parse format strings at compile time with
<code>constexpr</code> functions which has been demonstrated in the reference
implementation <a href="#14">[14]</a> and in <a href="#18">[18]</a>.
Unfortunately a satisfactory API cannot be provided using existing C++17
features. Ideally we would like to use a function call API similar to the one
proposed in this paper:</p>

<pre>
<code>template&lt;class String, class... Args&gt;
  string format(String fmt, const Args&amp;... args);</code></pre>

<p>where <code>String</code> is some type representing a compile-time format
string, for example</p>

<pre>
<code>struct MyString {
  static constexpr string_view value() { return string_view("{}", 2); }
};</code></pre>

<p>However, requiring a user to create a new type either manually or via a macro
for every format string is not acceptable. P0424R1 "Reconsidering literal
operator templates for strings" <a href="#15">[15]</a> provides a solution to this
problem based on user-defined literal operators. If this or other similar
proposal for compile-time strings is accepted into the standard, it should be
easy to provide additional formatting APIs that make use of this feature.
Obviously runtime checks will still be needed in cases where the format string is
not known at compile time, but as shown in <a href="#Benchmarks">Appendix A:
Benchmarks</a> even with runtime parsing performance can be on par with or
better than that of existing methods.</p>

<p>Compile-time processing of format strings <a
href="https://godbolt.org/g/wQyU21">can work with a user-defined type
<code>T</code></a> if the <code>formatter&lt;T&gt;::parse</code> function is
<code>constexpr</code>.

<h3><a name="Visitation">Argument visitation</a></h3>

<p>The argument visitation API can be used to implement dynamic format
specifiers, for example, width and precision passed as additional formatting
arguments as opposed to being encoded in the format string itself:</p>

<pre>
<code>int width = 10;
int precision = 3;
auto s = format("{0:{1}.{2}f}", 12.345678, width, precision);
// s == "    12.346"</code></pre>

<p>An example of a user-defined formatter with dynamic width:</p>

<pre>
<code>struct Answer {};

template&lt;&gt;
  struct formatter&lt;Answer&gt; {
    int width_arg_index = 0;

    // Parses dynamic width in the format "{&lt;digit&gt;}".
    auto parse(format_parse_context&amp; parse_ctx) {
      auto iter = parse_ctx.begin();
      auto get_char = [&amp;]() { return iter != parse_ctx.end() ? *iter : 0; };

      if (get_char() != '{')
        return iter;
      ++iter;
      char c = get_char();
      if (!std::isdigit(c) || (++iter, get_char()) != '}')
        throw format_error("invalid format");
      width_arg_index = c - '0';
      return ++iter;
    }

    auto format(Answer, format_context&amp; format_ctx) {
      auto arg = format_ctx.args().get(width_arg_index);
      int width = visit_format_arg([](auto value) -&gt; int {
        if constexpr (!std::is_integral_v&lt;decltype(value)&gt;)
          throw format_error("width is not integral");
        else if (value &lt; 0 || value &gt; std::numeric_limits&lt;int&gt;::max())
          throw format_error("invalid width");
        else
          return value;
        }, arg);
      return format_to(format_ctx.out(), "{:{}}", 42, width);
    }
  };

std::string s = format("{0:{1}}", Answer(), 10);
// s == "        42"</code></pre>

<p>In many cases formatting can be delegated to standard formatters which makes
manual handling of dynamic specifiers unneccessary, but the latter is still
important for more complex cases.</p>

<p>This API can also be used to implement a custom formatting engine, such as
the one compatible with the <code>printf</code> syntax, to provide some of the
benefits of the current proposal to the legacy code.</p>

<h3><a name="Impact">Impact on existing code</a></h3>

<p>
The proposed formatting API is defined in the new header
<code>&lt;format&gt;</code> and should have no impact on existing code.
</p>

<h2><a name="Wording">Proposed wording</a></h2>

<p>
Add a new entry <code>&lt;format&gt;</code> to table 18 in section
<a href="http://eel.is/c++draft/library#headers-2">15.5.1.2
[headers] paragraph 2</a>.
</p>

<p>Change in table 35 of
<a href="http://eel.is/c++draft/support.limits.general#3">
16.3.1 [support.limits.general] paragraph 3</a>:
<blockquote>
      <table border="1">
        <tr>
          <th align="center">Macro name</th>
          <th align="center">Value</th>
          <th align="center">Header(s)</th>
        </tr>
        <tr>
          <td>[&hellip;]</td>
          <td>[&hellip;]</td>
          <td>[&hellip;]</td>
        </tr>
        <tr>
          <td>__cpp_lib_filesystem</td>
          <td>201703L</td>
          <td>&lt;filesystem&gt;</td>
        </tr>
        <tr>
          <td><ins>__cpp_lib_format</ins></td>
          <td><ins>201811L</ins></td>
          <td><ins>&lt;format&gt;</ins></td>
        </tr>
        <tr>
          <td>__cpp_lib_gcd_lcm</td>
          <td>201606L</td>
          <td>&lt;numeric&gt;</td>
        </tr>
        <tr>
          <td>[&hellip;]</td>
          <td>[&hellip;]</td>
          <td>[&hellip;]</td>
        </tr>
      </table>
</blockquote>
</p>

<p>
Add a new section in 19 <a href="http://eel.is/c++draft/#utilities">[utilities]</a>.
</p>

<h3>19.20 Formatting utilities [format]</h3>

<!-- Synopsis example: http://eel.is/c%2B%2Bdraft/time#syn
     Code check: https://godbolt.org/z/-dsVgq -->
<h4>19.20.1 Header <code>&lt;format&gt;</code> synopsis [format.syn]</h4>

<pre>
<code>namespace std {
  // <a href="#format.error">[format.error]</a>, class format_error
  class format_error;

  // <a href="#format.formatter">[format.formatter]</a>, formatter
  template&lt;class charT&gt; class basic_format_parse_context;
  using format_parse_context = basic_format_parse_context&lt;char&gt;;
  using wformat_parse_context = basic_format_parse_context&lt;wchar_t&gt;;
  <!-- Exact string formatting iterator type is unspecified - it can be
       back_insert_iterator<string> or a similar type, possibly reused between
       containers with contiguous storage by type-erasing reallocation.
       Example of unspecified types as template params:
       http://eel.is/c++draft/time.duration.literals -->
  template&lt;class O, class charT&gt; requires OutputIterator&lt;O, const charT&amp;&gt;
    class basic_format_context;
  using format_context = basic_format_context&lt;<i>unspecified</i>, char&gt;;
  using wformat_context = basic_format_context&lt;<i>unspecified</i>, wchar_t&gt;;

  template&lt;class T, class charT = char&gt; struct formatter;
  <!-- Argument access API is provided for use cases such as dynamic width:
       https://godbolt.org/g/Mp93pN -->
  // <a href="#format.arguments">[format.arguments]</a>, arguments
  template&lt;class Context&gt; class basic_format_arg;

  template&lt;class Visitor, class Context&gt;
    <i>see below</i> visit_format_arg(Visitor&amp;&amp; vis, basic_format_arg&lt;Context&gt; arg);

  template&lt;class Context, class... Args&gt; struct format_arg_store; // <i>exposition only</i>

  template&lt;class Context&gt; class basic_format_args;
  using format_args = basic_format_args&lt;format_context&gt;;
  using wformat_args = basic_format_args&lt;wformat_context&gt;;

  template&lt;class O, class charT&gt;
    using format_args_t = basic_format_args&lt;basic_format_context&lt;O, charT&gt;&gt;;

  template&lt;class Context = format_context, class... Args&gt;
    format_arg_store&lt;Context, Args...&gt;
      make_format_args(const Args&amp;... args);
  template&lt;class... Args&gt;
    format_arg_store&lt;wformat_context, Args...&gt;
      make_wformat_args(const Args&amp;... args);

  // <a href="#format.functions">[format.functions]</a>, formatting functions
  template&lt;class... Args&gt;
    string format(string_view fmt, const Args&amp;... args);
  template&lt;class... Args&gt;
    wstring format(wstring_view fmt, const Args&amp;... args);

  string vformat(string_view fmt, format_args args);
  wstring vformat(wstring_view fmt, wformat_args args);

  template&lt;OutputIterator&lt;const char&amp;&gt; O, class... Args&gt;
    O format_to(O out, string_view fmt, const Args&amp;... args);
  template&lt;OutputIterator&lt;const wchar_t&amp;&gt; O, class... Args&gt;
    O format_to(O out, wstring_view fmt, const Args&amp;... args);

  template&lt;OutputIterator&lt;const char&amp;&gt; O&gt;
    O vformat_to(O out, string_view fmt, format_args_t&lt;O, char&gt; args);
  template&lt;OutputIterator&lt;const wchar_t&amp;&gt; O&gt;
    O vformat_to(O out, wstring_view fmt, format_args_t&lt;O, wchar_t&gt; args);

  template&lt;class O&gt;
    struct format_to_n_result {
      O out;
      iter_difference_t&lt;O&gt; size;
    };
  <!-- Formatted similar to std::mismatch: http://eel.is/c++draft/mismatch
       vformat_to_n is not provided but it can be with an iterator adapter. -->
  template&lt;OutputIterator&lt;const char&amp;&gt; O, class... Args&gt;
    format_to_n_result&lt;O&gt; format_to_n(O out, iter_difference_t&lt;O&gt; n,
                                      string_view fmt, const Args&amp;... args);
  template&lt;OutputIterator&lt;const wchar_t&amp;&gt; O, class... Args&gt;
    format_to_n_result&lt;O&gt; format_to_n(O out, iter_difference_t&lt;O&gt; n,
                                      wstring_view fmt, const Args&amp;... args);

  template&lt;class... Args&gt;
    size_t formatted_size(string_view fmt, const Args&amp;... args);
  template&lt;class... Args&gt;
    size_t formatted_size(wstring_view fmt, const Args&amp;... args);
}</code>
</pre>
<h4><a name="format.functions">19.20.2 Formatting functions [format.functions]</a></h4>

<dl>
<dt>
<pre><code>template&lt;class... Args&gt;
  string format(string_view fmt, const Args&amp;... args);</code></pre>
</dt>
<dd>
<p><i>Returns</i>: <code>vformat(fmt, make_format_args(args...))</code>.</p>
</dd>
</dl>

<dl>
<dt>
<pre><code>template&lt;class... Args&gt;
  wstring format(wstring_view fmt, const Args&amp;... args);</code></pre>
</dt>
<dd>
<p><i>Returns</i>: <code>vformat(fmt, make_wformat_args(args...))</code>.</p>
</dd>
</dl>

<dl>
<dt>
<pre><code>string vformat(string_view fmt, format_args args);
wstring vformat(wstring_view fmt, wformat_args args);</code></pre>
</dt>
<dd>
<p>
<!-- http://eel.is/c++draft/string.conversions#7 -->
<i>Returns</i>: A string object holding the character representation of
formatting arguments provided by <code>args</code> formatted according to
specifications given in <code>fmt</code>.
</p>
<p><i>Throws</i>: <code>format_error</code> if <code>fmt</code> is not a
valid format string.</p>
</dd>
</dl>

<dl>
<dt>
<pre><code>template&lt;OutputIterator&lt;const char&amp;&gt; O, class... Args&gt;
  O format_to(O out, string_view fmt, const Args&amp;... args);</code></pre>
</dt>
<dd>
<p>
  <i>Returns</i>:
  <code>vformat_to(out, fmt, make_format_args&lt;basic_format_context&lt;O, char&gt;&gt;(args...))</code>.
</p>
</dd>
</dl>

<dl>
<dt>
<pre><code>template&lt;OutputIterator&lt;const wchar_t&amp;&gt; O, class... Args&gt;
  O format_to(O out, wstring_view fmt, const Args&amp;... args);</code></pre>
</dt>
<dd>
<p>
  <i>Returns</i>:
  <code>vformat_to(out, fmt, make_format_args&lt;basic_format_context&lt;O, wchar_t&gt;&gt;(args...))</code>.
</p>
</dd>
</dl>

<dl>
<dt>
<pre><code>template&lt;OutputIterator&lt;const char&amp;&gt; O&gt;
  O vformat_to(O out, string_view fmt, format_args_t&lt;O, char&gt; args);
template&lt;OutputIterator&lt;const wchar_t&amp;&gt; O&gt;
  O vformat_to(O out, wstring_view fmt, format_args_t&lt;O, wchar_t&gt; args);</code></pre>
</dt>
<dd>

<p>
<i>Effects</i>:
Places the character representation of formatting arguments provided by
<code>args</code> formatted according to specifications given in
<code>fmt</code> into the range <code>[out, out + N)</code>, where
<code>N</code> is the formatted output size.
</p>
<p><i>Returns</i>: <code>out + N</code>.</p>
<p><i>Throws</i>: <code>format_error</code> if <code>fmt</code> is not a
valid format string.</p>
</dd>
</dl>

<dl>
<dt>
<pre><code>template&lt;OutputIterator&lt;const char&amp;&gt; O, class... Args&gt;
  format_to_n_result&lt;O&gt; format_to_n(O out, iter_difference_t&lt;O&gt; n,
                                    string_view fmt, const Args&amp;... args);
template&lt;OutputIterator&lt;const wchar_t&amp;&gt; O, class... Args&gt;
  format_to_n_result&lt;O&gt; format_to_n(O out, iter_difference_t&lt;O&gt; n,
                                    wstring_view fmt, const Args&amp;... args);</code></pre>
</dt>
<dd>

<p>
Let <code>N</code> be the formatted output size and <code>M</code> be
<code>min(max(n, 0), N)</code>.
</p>
<p>
<i>Effects</i>:
Places the character representation of formatting arguments provided by
<code>args</code> formatted according to specifications given in
<code>fmt</code> into the range <code>[out, out + M)</code>.
</p>
<p><i>Returns</i>: <code>{out + M, N}</code>.</p>
<p><i>Throws</i>: <code>format_error</code> if <code>fmt</code> is not a
valid format string.</p>
</dd>
</dl>

<dl>
<dt>
<pre><code>template&lt;class... Args&gt;
  size_t formatted_size(string_view fmt, const Args&amp;... args);
template&lt;class... Args&gt;
  size_t formatted_size(wstring_view fmt, const Args&amp;... args);</code></pre>
</dt>
<dd>
<p>
<i>Returns</i>: The number of characters in the character representation of
formatting arguments <code>args</code> formatted according to specifications
given in <code>fmt</code>.
</p>
<p><i>Throws</i>: <code>format_error</code> if <code>fmt</code> is not a
valid format string.</p>
</dd>
</dl>

<p>
The <code>fmt</code> string consists of zero or more <em>replacement
fields</em>, <em>escape sequences</em>, and ordinary multibyte characters. All
ordinary multibyte characters are copied unchanged to the output. An escape
sequence is one of <code>{{</code> or <code>}}</code>. It is replaced with
<code>{</code> or <code>}</code> respectively in the output. The syntax of
replacement fields is as follows:

<!-- The notation is the same as in http://eel.is/c++draft/facet.numpunct -->
<pre class="codeblock">
<code>replacement-field ::= '{' [arg-id] [':' format-spec] '}'
arg-id            ::= '0' | nonzero-digit [integer]
integer           ::= digit [integer]
nonzero-digit     ::= '1'...'9'
digit             ::= '0'...'9'</code>
</pre>
</p>

<p>
The <code>arg-id</code> field specifies the index of the argument in
<code>args</code> whose value is to be formatted and inserted into the output
instead of the replacement field. The optional <code>format-spec</code> field
specifies a non-default format for the replacement value.
</p>

<p>[ <i>Example:</i><pre>
<code>  string s = format("{0}-{{", 8); // s == "8-{"</code>
</pre> — <i>end example</i> ]
</p>

<p>
If the numeric <code>arg-id</code>s in a format string are 0, 1, 2, ... in
sequence, they can all be omitted (not just some) and the numbers 0, 1, 2, ...
will be automatically used in that order. Mixing automatic and manual indexing
is not allowed.
</p>

<p>[ <i>Example:</i><pre>
<code>  string s0 = format("{} to {}",   "a", "b"); // OK: automatic indexing
  string s1 = format("{1} to {0}", "a", "b"); // OK: manual indexing
  string s2 = format("{0} to {}",  "a", "b"); // Error: mixing automatic and manual indexing
  string s3 = format("{} to {1}",  "a", "b"); // Error: mixing automatic and manual indexing</code>
</pre> — <i>end example</i> ]
</p>

<p>
The <code>format-spec</code> field contains <em>format specifications</em> that
define how the value should be presented, including such details as field width,
alignment, padding, and decimal precision. Each type can define its own
<em>formatting mini-language</em> or interpretation of the
<code>format-spec</code> field. The syntax of format specifications is as
follows:

<pre class="codeblock">
<code>format-spec     ::= std-format-spec | custom-format-spec
std-format-spec ::= [[fill] align] [sign] ['#'] ['0'] [width] ['.' precision] [type]
fill            ::= &lt;a character other than '{' or '}'&gt;
align           ::= '&lt;' | '&gt;' | '=' | '^'
sign            ::= '+' | '-' | ' '
width           ::= nonzero-digit [integer] | '{' arg-id '}'
precision       ::= integer | '{' arg-id '}'
type            ::= 'a' | 'A' | 'b' | 'B' | 'c' | 'd' | 'e' | 'E' | 'f' | 'F' |
                    'g' | 'G' | 'n' | 'o' | 'p' | 's' | 'x' | 'X'</code>
</pre>
</p>

<p>
where <code>std-format-spec</code> defines a common formatting mini-language
supported by fundamental and string types, while <code>custom-format-spec</code>
is a placeholder for user-defined mini-languages. Some of the formatting options
are only supported by arithmetic types.
</p>

<p>
The <code>fill</code> character can be any character other than <code>'{'</code>
or <code>'}'</code>. The presence of a fill character is signaled by the
character following it, which must be one of the alignment options. If the
second character of <code>format-spec</code> is not a valid alignment option,
then it is assumed that both the fill character and the alignment option are
absent.
</p>

<p>Let <code>charT</code> be <code>decltype(fmt)::value_type</code>.</p>

<p>
The meaning of the various alignment options is as follows:
</p>

<table>
<thead>
<tr><th>Option</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'&lt;'</code></td>
<td>Forces the field to be left-aligned within the available space. This is
    the default for non-arithmetic types, <code>charT</code>, and
    <code>bool</code>, unless an integer presentation type is specified.</td>
</tr>
<tr>
<td><code>'&gt;'</code></td>
<td>Forces the field to be right-aligned within the available space. This is
    the default for arithmetic types other than <code>charT</code> and
    <code>bool</code> or when an integer presentation type is specified.</td>
</tr>
<tr>
<td><code>'='</code></td>
<td>Forces the padding to be placed after the sign (if any) but before the
    digits. This is used for printing fields in the form
    <code>+000000120</code>. This alignment option is only valid for arithmetic
    types other than <code>charT</code> and <code>bool</code> or when an
    integer presentation type is specified.</td>
</tr>
<tr>
<td><code>'^'</code></td>
<td>Forces the field to be centered within the available space by inserting
    <code>N / 2</code> and <code>N - N / 2</code> fill characters before and
    after the value respectively, where <code>N</code> is the total number of
    fill characters to insert.</td>
</tr>
</tbody>
</table>

<p>[ <i>Example:</i><pre>
<code>  char c = 120;
  string s0 = format("{:6}", 42);      // s0 == "    42"
  string s1 = format("{:6}", 'x');     // s1 == "x     "
  string s2 = format("{:*&lt;6}", 'x');   // s2 == "x*****"
  string s3 = format("{:*&gt;6}", 'x');   // s3 == "*****x"
  string s4 = format("{:*^6}", 'x');   // s4 == "**x***"
  string s5 = format("{:=6}", 'x');    // Error: '=' with charT and no integer presentation type
  string s6 = format("{:6d}", c);      // s6 == "   120"
  string s7 = format("{:=+06d}", c);   // s7 == "+00120"
  string s8 = format("{:6}", true);    // s8 == "true  "</code>
</pre> — <i>end example</i> ]
</p>

<p>
Note that unless a minimum field width is defined, the field width will be
determined by the width of the content, meaning that the alignment option has no
effect.
</p>

<p>
The <code>sign</code> option is only valid for arithmetic types other than
<code>charT</code> and <code>bool</code> or when an integer presentation type is
specified. It can be one of the following:
</p>

<table>
<thead>
<tr><th>Option</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'+'</code></td>
<td>Indicates that a sign should be used for both positive as well as negative
    numbers.</td>
</tr>
<tr>
<td><code>'-'</code></td>
<td>Indicates that a sign should be used only for negative numbers (this is
    the default behavior).</td>
</tr>
<tr>
<td>space</td>
<td>Indicates that a leading space should be used for positive numbers, and a
    minus sign for negative numbers.</td>
</tr>
</tbody>
</table>

<p>
The <code>sign</code> option applies to floating-point infinity and NaN.
</p>

<p>[ <i>Example:</i><pre>
<code>  double inf = std::numeric_limits&lt;double&gt;::infinity();
  double nan = std::numeric_limits&lt;double&gt;::quiet_NaN();
  string s0 = format("{0:} {0:+} {0:-} {0: }", 1);   // s0 == "1 +1 1  1"
  string s1 = format("{0:} {0:+} {0:-} {0: }", -1);  // s1 == "-1 -1 -1 -1"
  string s2 = format("{0:} {0:+} {0:-} {0: }", inf); // s2 == "inf +inf inf  inf"
  string s3 = format("{0:} {0:+} {0:-} {0: }", nan); // s3 == "nan +nan nan  nan"</code>
</pre> — <i>end example</i> ]
</p>

<p>
The <code>'#'</code> option causes the <em>alternate form</em> to be used for
the conversion. This option is only valid for arithmetic types other than
<code>charT</code> and <code>bool</code> or when an integer presentation type is
specified. For integers, when binary, octal, or hexadecimal output is used, this
option adds the respective
prefix <code>"0b"</code> (<code>"0B"</code>), <code>"0"</code>, or
<code>"0x"</code> (<code>"0X"</code>) to the output value. Whether the prefix
is lower-case or upper-case is determined by the case of the type format
specifier. For floating-point numbers the alternate form causes the result of the
conversion to always contain a decimal-point character, even if no digits follow
it. Normally, a decimal-point character appears in the result of these
conversions only if a digit follows it.
In addition, for <code>'g'</code> and <code>'G'</code> conversions, trailing
zeros are not removed from the result.
</p>

<p>
<code>width</code> is a decimal integer defining the minimum field width. If
not specified, then the field width will be determined by the content.
</p>

<p>
Preceding the <code>width</code> field by a zero (<code>'0'</code>) character
enables sign-aware zero-padding for arithmetic types. This is equivalent to a
<code>fill</code> character of <code>'0'</code> with an <code>alignment</code>
type of <code>'='</code>.
</p>

<p>
The <code>precision</code> field is a decimal integer defining the precision
or maximum field size. It can only be used with floating-point and string
types. For floating-point types this field specifies the formatting precision.
For string types it specifies how many characters will be used from the string.
</p>

<p>
Finally, the <code>type</code> determines how the data should be presented.
</p>

<p>The available string presentation types are:</p>

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'s'</code></td>
<td>Copies the string to the output.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'s'</code>.</td>
</tr>
</tbody>
</table>

<p>The available <code>charT</code> presentation types are:</p>

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'c'</code></td>
<td>Copies the character to the output.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'c'</code>.</td>
</tr>
</tbody>
</table>

<p>
Formatting of objects of arithmetic types and <code>const void*</code> is done
as if by calling <code>to_chars</code> and copying the output through the output
iterator of the context with additional padding and adjustments as per format
specifiers.
</p>

<p>
Let <code>[first, last)</code> be a range large enough to hold the
<code>to_chars</code> output and <code>value</code> be the formatting argument
value.
</p>

<p>The available integer presentation types and their mapping to
<code>to_chars</code> are:</p>

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'b'</code></td>
<td><code>to_chars(first, last, value, 2)</code>; using the <code>'#'</code>
    option with this type adds the prefix <code>"0b"</code> to the output.</td>
</tr>
<tr>
<td><code>'B'</code></td>
<td>The same as <code>'b'</code>, except that the <code>'#'</code> option adds
    the prefix <code>"0B"</code> to the output.</td>
</tr>
<tr>
<td><code>'d'</code></td>
<td><code>to_chars(first, last, value)</code>.</td>
</tr>
<tr>
<td><code>'o'</code></td>
<td><code>to_chars(first, last, value, 8)</code>; using the <code>'#'</code>
    option with this type adds the prefix <code>"0"</code> to the output.</td>
</tr>
<tr>
<td><code>'x'</code></td>
<td><code>to_chars(first, last, value, 16)</code>; using the <code>'#'</code>
    option with this type adds the prefix <code>"0x"</code> to the output.</td>
</tr>
<tr>
<td><code>'X'</code></td>
<td>The same as <code>'x'</code>, except that it uses uppercase letters for
    digits above 9 and the <code>'#'</code> option adds the prefix
    <code>"0X"</code> to the output.</td>
</tr>
<tr>
<td><code>'n'</code></td>
<td>The same as <code>'d'</code>, except that it uses the current global locale
  to insert the appropriate number separator characters.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'d'</code> if formatting argument type is not
    <code>charT</code> or <code>bool</code>.</td>
</tr>
</tbody>
</table>

<p>
Integer presentation types can also be used with <code>charT</code> and
<code>bool</code> values. Values of type <code>bool</code> are formatted using
textual representation, either <code>"true"</code> or <code>"false"</code>, if
the presentation type is not specified.
</p>

<p>[ <i>Example:</i><pre>
<code>  string s0 = format("{}", 42);                      // s0 == "42"
  string s1 = format("{0:b} {0:d} {0:o} {0:x}", 42); // s1 == "101010 42 52 2a"
  string s2 = format("{0:#x} {0:#X}", 42);           // s2 == "0x2a 0X2A"
  string s3 = format("{:n}", 1234);                  // s3 == "1,234" (depends on the locale)</code>
</pre> — <i>end example</i> ]
</p>

<p>The available floating-point presentation types and their mapping to
<code>to_chars</code> are:</p>

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'a'</code></td>
<td><code>to_chars(first, last, value, chars_format::hex, precision)</code>
  if <code>precision</code> is specified,
  <code>to_chars(first, last, value, chars_format::hex)</code> otherwise.</td>
</tr>
<tr>
<td><code>'A'</code></td>
<td>The same as <code>'a'</code>, except that it uses uppercase letters for
  digits above 9, <code>"P"</code> to indicate the exponent, <code>"INF"</code>
  for infinity, and <code>"NAN"</code> for NaN.</td>
</tr>
<tr>
<td><code>'e'</code></td>
<td><code>to_chars(first, last, value, chars_format::scientific, precision)</code>;
  <code>precision</code> defaults to 6 if not specified.</td>
</tr>
<tr>
<td><code>'E'</code></td>
<td>The same as <code>'e'</code>, except that it uses <code>"E"</code> to
  indicate exponent, <code>"INF"</code> for infinity, and <code>"NAN"</code> for
  NaN.</td>
</tr>
<tr>
<td><code>'f'</code></td>
<td><code>to_chars(first, last, value, chars_format::fixed, precision)</code>;
  <code>precision</code> defaults to 6 if not specified.</td>
</tr>
<tr>
<td><code>'F'</code></td>
<td>The same as <code>'f'</code>, except that it uses <code>"INF"</code> for
  infinity, and <code>"NAN"</code> for NaN.</td>
</tr>
<tr>
<td><code>'g'</code></td>
<td><code>to_chars(first, last, value, chars_format::general, precision)</code>;
  <code>precision</code> defaults to 6 if not specified.</td>
</tr>
<tr>
<td><code>'G'</code></td>
<td>The same as <code>'g'</code>, except that it uses <code>"E"</code> to
  indicate exponent, <code>"INF"</code> for infinity, and <code>"NAN"</code> for
  NaN.</td>
</tr>
<tr>
<td><code>'n'</code></td>
<td>The same as <code>'g'</code>, except that it uses the current global
    locale to insert the appropriate number separator characters.</td>
</tr>
<tr>
<td>none</td>
<td><code>to_chars(first, last, value, chars_format::general, precision)</code>
  if <code>precision</code> is specified, <code>to_chars(first, last, value)</code>
  otherwise.</td>
</tr>
</tbody>
</table>

<p>The available pointer presentation types and their mapping to
<code>to_chars</code> are:</p>

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'p'</code></td>
<td><code>to_chars(first, last, reinterpret_cast&lt;uintptr_t&gt;(value), 16)</code>
    with the prefix <code>"0x"</code> added to the output.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'p'</code>.</td>
</tr>
</tbody>
</table>

<p>
A format string that doesn't conform to the current specification is invalid.
</p>

<h4><a name="format.formatter">19.20.3 Formatter [format.formatter]</a></h4>

<!-- Based on http://eel.is/c++draft/unord.hash -->
<p>
The functions defined in <a href="#format.functions">[format.functions]</a> use
specializations of the class template <code>formatter</code> to format
individual arguments.
</p>

<p>
Each specialization of <code>formatter</code> is either enabled or disabled, as
described below. [ <i>Note:</i> Enabled specializations meet the
<i>Formatter</i> requirements, and disabled specializations do not.
<i>— end note</i> ] Each header that declares the template <code>formatter</code>
provides enabled specializations

<ul>
<li><pre><code>template&lt;&gt; struct formatter&lt;<i>charT</i>, <i>charT</i>&gt;;</code></pre>
<li><pre><code>template&lt;&gt; struct formatter&lt;char, wchar_t&gt;;</code></pre>
<li><pre><code>template&lt;&gt; struct formatter&lt;<i>charT</i>*, <i>charT</i>&gt;;</code></pre>
<li><pre><code>template&lt;&gt; struct formatter&lt;const <i>charT</i>*, <i>charT</i>&gt;;</code></pre>
<li><pre><code>template&lt;size_t N&gt; struct formatter&lt;const <i>charT</i>[N], <i>charT</i>&gt;;</code></pre>
<li><pre><code>template&lt;class traits, class Allocator&gt;
  struct formatter&lt;std::basic_string&lt;<i>charT</i>, traits, Allocator&gt;, <i>charT</i>&gt;;</code></pre>
<li><pre><code>template&lt;class traits&gt;
  struct formatter&lt;std::basic_string_view&lt;<i>charT</i>, traits&gt;, <i>charT</i>&gt;;</code></pre>
<li>specialiazations of <code>formatter</code> for <code>nullptr_t</code>,
<code>void*</code>, <code>const void*</code>, <code>bool</code>, and all
cv-unqualified standard integer types, extended integer types, and
floating-point types as the first template argument and <i>charT</i> as the
second template argument,
</ul>
where <i>charT</i> is <code>char</code> or <code>wchar_t</code>
(both sets of specializations are provided).
</p>

[ <i>Note:</i> Specializations such as <code>formatter&lt;wchar_t, char&gt;</code>
and <code>formatter&lt;const char*, wchar_t&gt;</code> that require implicit
multibyte / wide string or character conversion are intentionally disabled.
<i>— end note</i> ]

<p>
For any types <code>T</code> and <code>charT</code> for which neither the
library nor the user provides an explicit or partial specialization of the class
template <code>formatter</code>, <code>formatter&lt;T, charT&gt;</code> is
disabled.
</p>

<p>
If the library provides an explicit or partial specialization of
<code>formatter&lt;T, charT&gt;</code>, that specialization is enabled except as
noted otherwise.
</p>

<p>
If <code>F</code> is a disabled specialization of <code>formatter</code>, these
values are <code>false</code>: <code>is_default_constructible_v&lt;F&gt;</code>,
<code>is_copy_constructible_v&lt;F&gt;</code>,
<code>is_move_constructible_v&lt;F&gt;</code>,
<code>is_copy_assignable_v&lt;F&gt;</code>,
<code>is_move_assignable_v&lt;F&gt;</code>.
</p>

<p>
An enabled specialization <code>formatter&lt;T, charT&gt;</code> will satisfy
the <i>Formatter</i> requirements.
</p>

<p>[ <i>Example:</i><pre><code>  #include &lt;format&gt;

  enum color { red, green, blue };

  const char* color_names[] = { "red", "green", "blue" };

  template&lt;&gt; struct std::formatter&lt;color&gt; : std::formatter&lt;const char*&gt; {
    auto format(color c, format_context&amp; ctx) {
      return formatter&lt;const char*&gt;::format(color_names[c], ctx);
    }
  };

  struct err {};

  string s0 = std::format("{}", 42);     // OK: library-provided formatter
  string s1 = std::format("{}", L"foo"); // Ill-formed: disabled formatter
  string s2 = std::format("{}", red);    // OK: user-provided formatter
  string s3 = std::format("{}", err{});  // Ill-formed: disabled formatter</code>
</pre> — <i>end example</i> ]
</p>

<h5>19.20.3.1 <i>Formatter</i> requirements [formatter.requirements]</h5>

<!-- Based on http://eel.is/c++draft/hash.requirements -->
<p>
A type <code>F</code> meets the <i>Formatter</i> requirements if:
<ul class="itemize">
<li>it satisfies the <i>Cpp17DefaultConstructible</i>
    (Table <a href="http://eel.is/c++draft/utility.arg.requirements#tab:defaultconstructible">24</a>),
    <i>Cpp17CopyConstructible</i>
    (Table <a href="http://eel.is/c++draft/utility.arg.requirements#tab:copyconstructible">26</a>),
    <i>Cpp17CopyAssignable</i>
    (Table <a href="http://eel.is/c++draft/utility.arg.requirements#tab:copyassignable">28</a>), and
    <i>Cpp17Destructible</i>
    (Table <a href="http://eel.is/c++draft/utility.arg.requirements#tab:destructible">29</a>) requirements,
<li>it is swappable
    (<a href="http://eel.is/c++draft/swappable.requirements">[swappable.requirements]</a>)
    for lvalues, and
<li>the expressions shown in Table 1 are valid and have the indicated
    semantics.
</ul>
<p>
Given character type <code>charT</code>, output iterator type
<code>O</code>, and formatting argument type <code>T</code>, in
Table 1 <code>f</code> is a value of type <code>F</code>, <code>u</code> is an
lvalue of type <code>T</code>, <code>t</code> is a value of a type convertible
to (possibly const) <code>T</code>, <code>pc</code> is an lvalue of type
<code>basic_format_parse_context&lt;charT&gt;</code> (denoted by <code>PC</code>), and
<code>fc</code> is an lvalue of type
<code>basic_format_context&lt;O, charT&gt;</code> (denoted by
<code>FC</code>). <code>pc.begin()</code> points to the beginning of the
<code>format-spec</code> (<a href="#format.syntax">[format.syntax]</a>) portion
of the format string. If <code>format-spec</code> is empty then either
<code>pc.begin() == pc.end()</code> or <code>*pc.begin() == '}'</code>.
</p>

<table>
<caption>Table 1 — <i>Formatter</i> requirements</caption>
<thead>
<tr><th>Expression</th><th>Return type</th><th>Requirement</th></tr>
</thead>
<tbody>
<tr>
<td><code>f.parse(pc)</code></td>
<td><code>PC::iterator</code></td>
<td>
Shall parse <code>format-spec</code> for type <code>T</code>, store the parsed
specifiers in <code>*this</code>, and return an iterator past the end of the
parsed range.
</td>
</tr>
<tr>
<td><code>f.format(t,&nbsp;fc)</code></td>
<!-- FormatContext is a template param because we don't know the output
     iterator type. -->
<td><code>FC::iterator</code></td>
<td>
Shall format <code>t</code> according to the specifiers stored in
<code>*this</code>, write the output to <code>fc.out()</code> and return an
iterator past the end of the output range.
</td>
</tr>
<tr>
<td><code>f.format(u,&nbsp;fc)</code></td>
<td><code>FC::iterator</code></td>
<td>Shall not modify u.</td>
</tr>
</tbody>
</table>

<h5>19.20.3.2 Class template <code>basic_format_parse_context</code>
[format.parse_context]</h5>

<!-- Code check: https://godbolt.org/g/ymJijC -->
<pre>
<code>namespace std {
  template&lt;class charT&gt;
  class basic_format_parse_context {
  public:
    using char_type = charT;
    using const_iterator = typename basic_string_view&lt;charT&gt;::const_iterator;
    using iterator = const_iterator;

  private:
    iterator begin_;                              // <i>exposition only</i>
    iterator end_;                                // <i>exposition only</i>
    enum indexing { unknown, manual, automatic }; // <i>exposition only</i>
    indexing indexing_;                           // <i>exposition only</i>
    size_t next_arg_id_;                          // <i>exposition only</i>

  public:
    explicit constexpr basic_format_parse_context(basic_string_view&lt;charT&gt; fmt) noexcept;
    basic_format_parse_context(const basic_format_parse_context&amp;) = delete;
    basic_format_parse_context&amp; operator=(const basic_format_parse_context&amp;) = delete;

    constexpr const_iterator begin() const noexcept;
    constexpr const_iterator end() const noexcept;
    constexpr void advance_to(iterator it);

    constexpr size_t next_arg_id();
    constexpr void check_arg_id(size_t id);
  };
}</code>
</pre>

<p>
An instance of <code>basic_format_parse_context</code> holds the format
string parsing state consisting of the format string range being parsed and the
argument counter for automatic indexing.
</p>

<dl>
<!--dt><code>using const_iterator = <i>implementation-defined</i>;</code></dt>
<dd>
<p>A type that meets the requirements of a constant random access iterator
(<a href="http://eel.is/c++draft/random.access.iterators"
>[random.access.iterators])</a> and of a contiguous iterator
(<a href="http://eel.is/c++draft/iterator.requirements.general"
>[iterator.requirements.general]</a>) whose <code>value_type</code> is the
template parameter <code>charT</code>.</p>
</dd-->
<dt><code>explicit constexpr basic_format_parse_context(basic_string_view&lt;charT&gt;	fmt) noexcept;</code></dt>
<dd>
<p><i>Effects</i>: Initializes <code>begin_</code> with <code>fmt.begin()</code>,
<code>end_</code> with <code>fmt.end()</code>, <code>indexing_</code> with
<code>unknown</code>, and <code>next_arg_id_</code> with <code>0</code>.</p>
</dd>
<dt><code>constexpr const_iterator begin() const noexcept;</code></dt>
<dd>
<!-- Similar to http://eel.is/c++draft/string.iterators -->
<p><i>Returns</i>: <code>begin_</code>.</p>
</dd>
<dt><code>constexpr const_iterator end() const noexcept;</code></dt>
<dd>
<p><i>Returns</i>: <code>end_</code>.</p>
</dd>
<dt><code>constexpr void advance_to(iterator it);</code></dt>
<dd>
<p><i>Requires</i>: <code>end()</code> shall be reachable from <code>it</code>.</p>
<p><i>Effects</i>: Equivalent to: <code>begin_ = it;</code></p>
</dd>
<dt><code>constexpr size_t next_arg_id();</code></dt>
<dd>
<p><i>Effects</i>: Equivalent to:
<pre><code>  if (indexing_ == unknown)
    indexing_ = automatic;
  return next_arg_id_++;</code></pre></p>
<p><i>Throws</i>: <code>format_error</code> if <code>indexing_ == manual</code>
which indicates mixing of automatic and manual argument indexing.</p>
</dd>
<dt><code>constexpr void check_arg_id(size_t id);</code></dt>
<dd>
<p><i>Effects</i>: Equivalent to:
<pre><code>  if (indexing_ == unknown)
    indexing_ = manual;</code></pre></p>
<p><i>Throws</i>: <code>format_error</code> if
<code>indexing_ == automatic</code> which indicates mixing of automatic and
manual argument indexing.</p>
</dd>
</dl>

<h5>19.20.3.3 Class template <code>basic_format_context</code>
[format.context]</h5>

<!-- Code check: https://godbolt.org/g/8xNnUy -->
<pre>
<code>namespace std {
  template&lt;class O, class charT&gt; requires OutputIterator&lt;O, const charT&amp;&gt;
  class basic_format_context {
    basic_format_parse_context&lt;charT&gt; parse_context_; // <i>exposition only</i>
    basic_format_args&lt;basic_format_context&gt; args_;    // <i>exposition only</i>
    O out_;                                           // <i>exposition only</i>

  public:
    using iterator = O;
    using char_type = charT;

    template&lt;class T&gt;
      using formatter_type = formatter&lt;T&gt;;

    basic_format_parse_context&lt;charT&gt;&amp; parse_context() noexcept;
    basic_format_arg&lt;basic_format_context&gt; arg(size_t id) const;

    iterator out();
    void advance_to(iterator it);
  };
}</code>
</pre>

<p>
An instance of <code>basic_format_context</code> holds formatting state
consisting of the format string parsing context, formatting arguments, and
output iterator.
</p>

<dl>
<dt><code>basic_format_parse_context&lt;charT&gt;&amp; parse_context() noexcept;</code></dt>
<dd>
<p><i>Returns</i>: <code>parse_context_</code>.</p>
</dd>
<dt><code>basic_format_arg&lt;basic_format_context&gt; arg(size_t id) const;</code></dt>
<dd>
<p><i>Returns</i>: <code>args_.get(id)</code>.</p>
</dd>
<dt><code>iterator out();</code></dt>
<dd>
<p><i>Returns</i>: <code>out_</code>.</p>
</dd>
<dt><code>void advance_to(iterator it);</code></dt>
<dd>
<p><i>Effects</i>: Equivalent to: <code>out_ = it;</code></p>
</dd>
</dl>
<p>[ <i>Example:</i><pre>
<code>  struct S {
    int value;
  };

  template&lt;&gt; struct std::formatter&lt;S&gt; {
    int width_arg_id = 0;

    // Parses a width argument id in the format { &lt;digit&gt; }.
    constexpr auto parse(format_parse_context&amp; ctx) {
      auto iter = ctx.begin();
      auto get_char = [&amp;]() { return iter != ctx.end() ? *iter : 0; };
      if (get_char() != '{')
        return iter;
      ++iter;
      char c = get_char();
      if (!std::isdigit(c) || (++iter, get_char()) != '}')
        throw format_error("invalid format");
      width_arg_id = c - '0';
      ctx.check_arg_id(width_arg_id);
      return ++iter;
    }

    // Formats S with width given by the argument width_arg_id.
    auto format(S s, format_context&amp; ctx) {
      int width = visit_format_arg([](auto value) -&gt; int {
        if constexpr (!std::is_integral_v&lt;decltype(value)&gt;)
          throw format_error("width is not integral");
        else if (value &lt; 0 || value &gt; std::numeric_limits&lt;int&gt;::max())
          throw format_error("invalid width");
        else
          return value;
        }, ctx.arg(width_arg_id));
      return format_to(ctx.out(), "{0:{1}}", s.value, width);
    }
  };

  std::string s = format("{0:{1}}", S{42}, 10); // s == "        42"</code></pre> — <i>end example</i> ]
</p>

<h4><a name="format.arguments">19.20.4 Arguments [format.arguments]</a></h4>
<h5>19.20.4.1 Class template <code>basic_format_arg</code> [format.arg]</h5>
<!-- Argument access API is provided for use cases such as dynamic width:
     https://godbolt.org/g/wNhkk7 -->

<pre>
<code>namespace std {
  template&lt;class Context&gt;
  class basic_format_arg {
  public:
    class handle;

    using char_type = typename Context::char_type;                       <i>// exposition only</i>

    variant&lt;monostate, bool, char_type,
            int, unsigned int, long long int, unsigned long long int,
            double, long double,
            const char_type*, basic_string_view&lt;char_type&gt;,
            const void*, handle&gt; value;                                  <i>// exposition only</i>

    basic_format_arg() noexcept;

    template&lt;Integral I&gt; explicit basic_format_arg(I val) noexcept;      <i>// exposition only</i>
    explicit basic_format_arg(float val) noexcept;                       <i>// exposition only</i>
    explicit basic_format_arg(double val) noexcept;                      <i>// exposition only</i>
    explicit basic_format_arg(long double val) noexcept;                 <i>// exposition only</i>
    explicit basic_format_arg(const char_type* val) noexcept;            <i>// exposition only</i>
    explicit basic_format_arg(const void* val) noexcept;                 <i>// exposition only</i>
    explicit basic_format_arg(nullptr_t) noexcept;                       <i>// exposition only</i>

    template&lt;class traits&gt;
      explicit basic_format_arg(
        basic_string_view&lt;char_type, traits&gt; val) noexcept;              <i>// exposition only</i>

    template&lt;class traits, class Allocator&gt;
      explicit basic_format_arg(
        const basic_string&lt;char_type, traits, Allocator&gt;&amp; val) noexcept; <i>// exposition only</i>

    template&lt;class T&gt;
      explicit basic_format_arg(const T&amp; val) noexcept;                  <i>// exposition only</i>

    explicit operator bool() const noexcept;

    bool is_arithmetic() const noexcept;
    bool is_integral() const noexcept;
  };
}</code>
</pre>

<!-- Wording is similar to http://www.eel.is/c++draft/string.view -->
<p>
An instance of <code>basic_format_arg</code> provides access to a formatting
argument for user-defined formatters.
</p>

<dl>
<dt><code>basic_format_arg() noexcept;</code></dt>
<dd><p><i>Ensures</i>: <code>!(*this)</code>.</p></dd>

<dt><code>template&lt;Integral I&gt;
explicit basic_format_arg(I val) noexcept;</code></dt>
<dd>
<p><i>Effects</i>:
<ul class="itemize">
<li>if <code>I</code> is <code>bool</code> or <code>char_type</code>,
    initializes <code>value</code> with <code>val</code>,
<li>if <code>I</code> is <code>char</code> and <code>char_type</code> is
    <code>wchar_t</code>, initializes <code>value</code> with
    <code>static_cast&lt;wchar_t&gt;(val)</code>,
<li>if <code>I</code> is a standard signed integer type or an extended signed
    integer type and <code>sizeof(I) &lt;= sizeof(int)</code>, initializes
    <code>value</code> with <code>static_cast&lt;int&gt;(val)</code>,
<li>if <code>I</code> is a standard unsigned integer type or an extended
    unsigned integer type and <code>sizeof(I) &lt;= sizeof(unsigned int)</code>,
    initializes <code>value</code> with
    <code>static_cast&lt;unsigned int&gt;(val)</code>,
<li>if <code>I</code> is a standard signed integer type or an extended signed
    integer type and <code>sizeof(I) &lt;= sizeof(long long int)</code>,
    initializes <code>value</code> with
    <code>static_cast&lt;long long int&gt;(val)</code>,
<li>if <code>I</code> is a standard unsigned integer type or an extended
    unsigned integer type and
    <code>sizeof(I) &lt;= sizeof(unsigned long long int)</code>, initializes
    <code>value</code> with
    <code>static_cast&lt;unsigned long long int&gt;(val)</code>,
<li>otherwise the program is ill-formed.
</ul>
</p>
</dd>

<dt><code>explicit basic_format_arg(float val) noexcept;</code></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>value</code> with
  <code>static_cast&lt;double&gt;(val)</code>.</p>
</dd>

<dt><code>explicit basic_format_arg(double val) noexcept;<br>
explicit basic_format_arg(long double val) noexcept;<br>
explicit basic_format_arg(const char_type* val) noexcept;<br>
explicit basic_format_arg(const void* val) noexcept;</code></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>value</code> with
  <code>val</code>.</p>
</dd>

<dt><code>explicit basic_format_arg(nullptr_t) noexcept;</code></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>value</code> with
  <code>static_cast&lt;const void*&gt;(nullptr)</code>.</p>
</dd>

<dt><pre><code>template&lt;class traits&gt;
  explicit basic_format_arg(basic_string_view&lt;char_type, traits&gt; val) noexcept;</code></pre></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>value</code> with
  <code>basic_string_view&lt;char_type&gt;(val.data(), val.size())</code>.</p>
</dd>

<dt><pre><code>template&lt;class traits, class Allocator&gt;
  explicit basic_format_arg(
    const basic_string&lt;char_type, traits, Allocator&gt;&amp; val) noexcept;</code></pre></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>value</code> with
  <code>basic_string_view&lt;char_type&gt;(val.data(), val.size())</code>.</p>
</dd>

<dt><pre><code>template&lt;class T&gt; explicit basic_format_arg(const T&amp; val) noexcept;</code></pre></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>value</code> with
  <code>handle(val)</code>.</p>
  <p><i>Remarks</i>: This constructor shall not participate in overload
  resolution unless <code>formatter&lt;T, char_type&gt;</code> is enabled.</p>
</dd>

<dt><code>explicit operator bool() const noexcept;</code></dt>
<dd>
<p><i>Returns</i>: <code>!holds_alternative&lt;monostate&gt;(value)</code>.</p>
</dd>
<dt><code>bool is_arithmetic() const noexcept;</code></dt>
<dd>
<p><i>Returns</i>: <code>visit([](auto v) { return is_arithmetic_v&lt;decltype(v)&gt;; }, value)</code>.</p>
</dd>
<dt><code>bool is_integral() const noexcept;</code></dt>
<dd>
<p><i>Returns</i>: <code>visit([](auto v) { return is_integral_v&lt;decltype(v)&gt;; }, value)</code>.</p>
</dd>
</dl>

[ <i>Note:</i> Implementations are encouraged to take advantage of the
ordering of the alternative types in <code>value</code> and implement
<code>is_arithmetic</code> and <code>is_integral</code> more efficiently as a
range check on <code>value.index()</code>.
<i>— end note</i> ]

<!-- Nested class example: http://eel.is/c++draft/istream::sentry -->
<pre>
<code>namespace std {
  template&lt;class Context&gt;
  class basic_format_arg&lt;Context&gt;::handle {
    const void* ptr_;                                         // <i>exposition only</i>
    void (*format_)(Context&amp;, const void*);                   // <i>exposition only</i>

  public:
    template&lt;class T&gt; explicit handle(const T&amp; val) noexcept; // <i>exposition only</i>

    void format(Context&amp; ctx) const;
  };
}</code>
</pre>

<p>
The class <code>handle</code> allows formatting an object of a non-fundamental
type.
</p>

<dl>
<dt><code>template&lt;class T&gt; explicit handle(const T&amp; val) noexcept;</code></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>ptr_</code> with <code>&amp;val</code>
  and <code>format_</code> with <pre><code>[](Context&amp; ctx, const void* ptr) {
    typename Context::template formatter_type&lt;T&gt; f;
    ctx.parse_context().advance_to(f.parse(ctx.parse_context()));
    ctx.advance_to(f.format(*static_cast&lt;const T*&gt;(ptr), ctx));
  }</code></pre></p>
</dd>
<dt><code>void format(Context&amp; ctx) const;</code></dt>
<dd>
  <p><i>Effects</i>: Equivalent to: <code>format_(ctx, ptr_);</code></p>
</dd>
</dl>

<h5>19.20.4.2 Argument visitation [format.visit]</h5>

<!-- Similar to http://eel.is/c++draft/variant#visit -->
<dl>
<dt><pre><code>template&lt;class Visitor, class Context&gt;
  <i>see below</i> visit_format_arg(Visitor&amp;&amp; vis, basic_format_arg&lt;Context&gt; arg);</code></pre></dt>
<dd>
<p><i>Returns:</i> <code>visit(vis, arg.value)</code>.</p>
<p><i>Remarks:</i>
The return type is the type of the expression in the <i>Returns</i> section.
</p>
</dd>
</dl>

<h5>19.20.4.3 Class template <code>format_arg_store</code></h5>

<pre>
<code>namespace std {
  template&lt;class Context, class... Args&gt;
  struct format_arg_store { // <i>exposition only</i>
    array&lt;basic_format_arg&lt;Context&gt;, sizeof...(Args)&gt; args;
  };
}</code>
</pre>

<h5>19.20.4.4 Class template <code>basic_format_args</code></h5>

<pre>
<code>namespace std {
  template&lt;class Context&gt;
  class basic_format_args {
    size_t size_;                           // <i>exposition only</i>
    const basic_format_arg&lt;Context&gt;* data_; // <i>exposition only</i>

  public:
    basic_format_args() noexcept;

    template&lt;class... Args&gt;
      basic_format_args(const format_arg_store&lt;Context, Args...&gt;&amp; store) noexcept;

    basic_format_arg&lt;Context&gt; get(size_t i) const noexcept;
  };
}</code>
</pre>

<!-- Wording is similar to http://eel.is/c++draft/initializer_list.syn -->
<p>
An instance <code>basic_format_args</code> provides access to formatting
arguments.
</p>

<dl>
<dt><code>basic_format_args() noexcept;</code></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>size_</code> with <code>0</code>.</p>
</dd>
</dl>

<dl>
<dt><pre><code>template&lt;class... Args&gt;
  basic_format_args(const format_arg_store&lt;Context, Args...&gt;&amp; store) noexcept;</code></pre></dt>
<dd>
  <p><i>Effects</i>: Initializes <code>size_</code> with
  <code>sizeof...(Args)</code> and <code>data_</code> with <code>store.args.data()</code>.
</p>
</dd>
</dl>

<dl>
<dt><code>basic_format_arg&lt;Context&gt; get(size_t i) const noexcept;</code></dt>
<dd>
<p><i>Returns</i>: <code>i &lt; size_ ? data_[i] : basic_format_arg&lt;Context&gt;()</code>.</p>
</dd>
</dl>

[ <i>Note:</i> Implementations are encouraged to optimize the representation of
<code>basic_format_args</code> for small number of formatting arguments by
storing indices of type alternatives separately from values and packing the
former. <i>— end note</i> ]

<h5>19.20.4.5 Function template <code>make_format_args</code></h5>

<dl>
<dt>
<pre><code>template&lt;class Context = format_context, class... Args&gt;
  format_arg_store&lt;Context, Args...&gt; make_format_args(const Args&amp;... args);</code></pre>
</dt>
<dd>
  <p><i>Returns</i>: <code>{basic_format_arg&lt;Context&gt;(args)...}</code>.</p>
</dd>
</dl>

<h5>19.20.4.6 Function template <code>make_wformat_args</code></h5>

<dl>
<dt>
<pre><code>template&lt;class... Args&gt;
  format_arg_store&lt;wformat_context, Args...&gt; make_wformat_args(const Args&amp;... args);</code></pre>
</dt>
<dd>
  <p><i>Returns</i>: <code>{basic_format_arg&lt;wformat_context&gt;(args)...}</code>.</p>
</dd>
</dl>

<h4><a name="format.error">19.20.5 Class <code>format_error</code> [format.error]</a></h4>

<!-- Wording similar to http://eel.is/c++draft/range.error -->
<pre>
<code>namespace std {
  class format_error : public runtime_error {
  public:
    explicit format_error(const string&amp; what_arg);
    explicit format_error(const char* what_arg);
  };
}</code>
</pre>

<p>
The class <code>format_error</code> defines the type of objects thrown as
exceptions to report errors from the formatting library.
</p>

<dl>
<dt><code>format_error(const string&amp; what_arg);</code></dt>
<dd>
  <p><i>Ensures</i>: <code>strcmp(what(), what_arg.c_str()) == 0</code>.
  </p>
</dd>
<dt><code>format_error(const char* what_arg);</code></dt>
<dd>
  <p><i>Ensures</i>: <code>strcmp(what(), what_arg) == 0</code>.</p>
</dd>
</dl>

<h2><a name="RelatedWork">Related work</a></h2>

<p>
The Boost Format library <a href="#8">[8]</a> is an established formatting
library that uses <code>printf</code>-like format string syntax with extensions.
The main differences between this library and the current proposal are:
</p>

<ul>
<li>Syntax: for the reasons described in section
<a href="Syntax">Format String Syntax</a> this proposal
uses a new syntax instead of extending the <code>printf</code> one. This allows much
simpler and easier to parse grammar, not burdened by legacy specifiers used to
convey type information. For example, Boost Format has two ways
to refer to an argument by index and allows but ignores some format specifiers.
<li>API: Boost Format uses <code>operator%</code> to pass formatting arguments
while this proposal uses variadic function templates.
<li>Performance: the implementation of this proposal is several times faster
that the implementation of Boost Format on tinyformat benchmarks
<a href="#9">[9]</a>, generates smaller binary code and is faster to compile.
</ul>

<p>
A <code>printf</code>-like Interface for the Streams Library <a href="#10">[10]</a>
is similar to the Boost Format library but uses variadic templates instead of
<code>operator%</code>. Unfortunately it hasn't been updated since 2013 and the
same arguments about format string syntax apply to it.
</p>

<p>
The FastFormat library <a href="#11">[11]</a> is another well-known formatting
library. Similarly to this proposal, FastFormat uses brace-delimited format
specifiers, but otherwise the format string syntax is different and the library
has significant limitations <a href="#12">[12]</a>:

<blockquote>
Three features that have no hope of being accommodated within the current
design are:

<ul>
<li>Leading zeros (or any other non-space padding)
<li>Octal/hexadecimal encoding
<li>Runtime width/alignment specification
</ul>
</blockquote>
</p>

<p>
Formatting facilities of the Folly library <a href="#13">[13]</a> are the
closest to the current proposal. Folly also uses Python-like format string
syntax nearly identical to the one described here. However, the API details are
quite different. The current proposal tries to address performance and code
bloat issues that are largely ignored by Folly Format. For instance formatting
functions in Folly Format are parameterized on all argument types while in this
proposal, only the inlined wrapper functions are, which results in much smaller
binary code and better compile times.
</p>

<h2><a name="Implementation">Implementation</a></h2>

<p>
An implementation of this proposal is available in the <code>std</code> branch
of the open-source fmt library <a href="#14">[14]</a>.
</p>

<h2><a name="Acknowledgements">Acknowledgements</a></h2>

<p>
Thanks to Antony Polukhin, Beman Dawes, Bengt Gustafsson, Eric Niebler,
Jason McKesson, Jeffrey Yasskin, Joël Lamotte, Lars Gullik Bjønnes, Lee Howes,
Louis Dionne, Matt Clarke, Michael Park, Sergey Ignatchenko, Thiago Macieira,
Zach Laine, Zhihao Yuan and participants of the Library Evolution Working Group
for their feedback, support, constructive criticism and contributions to the
proposal. Special thanks to Howard Hinnant who encouraged me to write the
proposal and gave useful early advice on how to go about it.
</p>

<p>
The format string syntax is based on the Python documentation
<a href="#3">[3]</a>.
</p>

<h2><a name="References">References</a></h2>

<p>
<a name="1">[1]</a>
<cite>The <code>fprintf</code> function. ISO/IEC 9899:2011. 7.21.6.1.</cite><br>
<a name="2">[2]</a>
<cite><a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html">
fprintf, printf, snprintf, sprintf - print formatted output</a>. The Open
Group Base Specifications Issue 6 IEEE Std 1003.1, 2004 Edition.</cite><br>
<a name="3">[3]</a>
<cite><a href="https://docs.python.org/3/library/string.html#format-string-syntax">
6.1.3. Format String Syntax</a>. Python 3.5.2 documentation.</cite><br>
<a name="4">[4]</a>
<cite><a href="https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx">
String.Format Method</a>. .NET Framework Class Library.</cite><br>
<a name="5">[5]</a>
<cite><a href="https://doc.rust-lang.org/std/fmt/">
Module <code>std::fmt</code></a>. The Rust Standard Library.</cite><br>
<a name="6">[6]</a>
<cite><a href="https://msdn.microsoft.com/en-us/library/56e442dc(v=vs.120).aspx">
Format Specification Syntax: printf and wprintf Functions</a>. C++ Language and
Standard Libraries.</cite><br>
<a name="7">[7]</a>
<cite><a href="ftp://ftp.gnu.org/old-gnu/Manuals/gawk-3.1.0/html_chapter/gawk_11.html">
10.4.2 Rearranging printf Arguments</a>. The GNU Awk User's Guide.</cite><br>
<a name="8">[8]</a>
<cite><a href="http://www.boost.org/doc/libs/1_63_0/libs/format/">
Boost Format library</a>. Boost 1.63 documentation.</cite><br>
<a name="9">[9]</a>
<cite><a href="https://github.com/fmtlib/fmt#speed-tests">
Speed Test</a>. The fmt library repository.</cite><br>
<a name="10">[10]</a>
<cite><a href="https://isocpp.org/files/papers/n3716.html">
A printf-like Interface for the Streams Library (revision 1)</a>.</cite><br>
<a name="11">[11]</a>
<cite><a href="http://www.fastformat.org/">
The FastFormat library website</a>.</cite><br>
<a name="12">[12]</a>
<cite><a href="https://accu.org/index.php/journals/1539">
An Introduction to Fast Format (Part 1): The State of the Art</a>.
Overload Journal #89 - February 2009</cite><br>
<a name="13">[13]</a>
<cite><a href="https://github.com/facebook/folly">
The folly library repository</a>.</cite><br>
<a name="14">[14]</a>
<cite><a href="https://github.com/fmtlib/fmt">
The fmt library repository</a>.</cite><br>
<a name="15">[15]</a>
<cite><a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0424r1.pdf">
P0424: Reconsidering literal operator templates for strings</a>.</cite><br>
<a name="16">[16]</a>
<cite><a href="https://howardhinnant.github.io/date/d0355r4.html">
D0355: Extending &lt;chrono&gt; to Calendars and Time Zones</a>.</cite><br>
<a name="17">[17]</a>
<cite><a
href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0067r1.html">
P0067: Elementary string conversions</a>.</cite><br>
<a name="18">[18]</a>
<cite><a href="https://github.com/mpark/format">
MPark.Format: Compile-time Checked, Type-Safe Formatting in C++14</a>.</cite>
<br>
<a name="19">[19]</a>
<cite><a href="https://github.com/google/benchmark">
Google Benchmark: A microbenchmark support library</a>.</cite><br>
<a name="20">[20]</a>
<cite><a href="http://open-std.org/JTC1/SC22/WG21/docs/papers/2015/n4412.html">
N4412: Shortcomings of iostreams</a>.</cite><br>
</p>

<h2><a name="Benchmarks">Appendix A: Benchmarks</a></h2>

To demonstrate that the formatting functions described in this paper can be
implemented efficiently, we compare the reference implementation [14] of
<code>format</code> and <code>format_to</code> to <code>sprintf</code>,
<code>ostringstream</code> and <code>to_string</code> on the following
benchmark. This benchmark generates a set of integers with random numbers of
digits, applies each method to convert each integer into a string (either
<code>std::string</code> or a char buffer depending on the API) and uses the
Google Benchmark library [19] to measure timings:

<pre><code>  #include &lt;algorithm&gt;
  #include &lt;cmath&gt;
  #include &lt;cstdio&gt;
  #include &lt;limits&gt;
  #include &lt;sstream&gt;
  #include &lt;string&gt;
  #include &lt;utility&gt;
  #include &lt;vector&gt;

  #include &lt;benchmark/benchmark.h&gt;
  #include &lt;fmt/format.h&gt;

  // Returns a pair with the smallest and the largest value of integral type T
  // with the given number of digits.
  template&lt;typename T&gt;
  std::pair&lt;T, T&gt; range(int num_digits) {
    T first = std::pow(T(10), num_digits - 1);
    int max_digits = std::numeric_limits&lt;T&gt;::digits10 + 1;
    T last = num_digits &lt; max_digits ? first * 10 - 1 :
                                 std::numeric_limits&lt;T&gt;::max();
    return {num_digits &gt; 1 ? first : 0, last};
  }

  // Generates values of integral type T with random number of digits.
  template&lt;typename T&gt;
  std::vector&lt;T&gt; generate_random_data(int numbers_per_digit) {
    int max_digits = std::numeric_limits&lt;T&gt;::digits10 + 1;
    std::vector&lt;T&gt; data;
    data.reserve(max_digits * numbers_per_digit);
    for (int i = 1; i &lt;= max_digits; ++i) {
      auto r = range&lt;T&gt;(i);
      auto value = r.first;
      std::generate_n(std::back_inserter(data), numbers_per_digit, [=]() mutable {
        T result = value;
        value = value &lt; r.second ? value + 1 : r.first;
        return result;
      });
    }
    std::random_shuffle(data.begin(), data.end());
    return data;
  }

  auto data = generate_random_data&lt;int&gt;(1000);

  void sprintf(benchmark::State &s) {
    size_t result = 0;
    while (s.KeepRunning()) {
      for (auto i: data) {
        char buffer[12];
        result += std::sprintf(buffer, &quot;%d&quot;, i);
      }
    }
    benchmark::DoNotOptimize(result);
  }
  BENCHMARK(sprintf);

  void ostringstream(benchmark::State &s) {
    size_t result = 0;
    while (s.KeepRunning()) {
      for (auto i: data) {
        std::ostringstream ss;
        ss &lt;&lt; i;
        result += ss.str().size();
      }
    }
    benchmark::DoNotOptimize(result);
  }
  BENCHMARK(ostringstream);

  void to_string(benchmark::State &s) {
    size_t result = 0;
    while (s.KeepRunning()) {
      for (auto i: data)
        result += std::to_string(i).size();
    }
    benchmark::DoNotOptimize(result);
  }
  BENCHMARK(to_string);

  void format(benchmark::State &s) {
    size_t result = 0;
    while (s.KeepRunning()) {
      for (auto i: data)
        result += fmt::format(&quot;{}&quot;, i).size();
    }
    benchmark::DoNotOptimize(result);
  }
  BENCHMARK(format);

  void format_to(benchmark::State &s) {
    size_t result = 0;
    while (s.KeepRunning()) {
      for (auto i: data) {
        char buffer[12];
        result += fmt::format_to(buffer, &quot;{}&quot;, i) - buffer;
      }
    }
    benchmark::DoNotOptimize(result);
  }
  BENCHMARK(format_to);

  BENCHMARK_MAIN();</code></pre>

The benchmark was compiled with clang (Apple LLVM version 9.0.0
clang-900.0.39.2) with <code>-O3 -DNDEBUG</code> and run on a macOS system.
Below are the results:

<pre>
  Run on (4 X 3100 MHz CPU s)
  2018-01-27 07:12:00
  Benchmark              Time           CPU Iterations
  ----------------------------------------------------
  sprintf           882311 ns     881076 ns        781
  ostringstream    2892035 ns    2888975 ns        242
  to_string        1167422 ns    1166831 ns        610
  format            675636 ns     674382 ns       1045
  format_to         499376 ns     498996 ns       1263
</pre>

The <code>format</code> and <code>format_to</code> functions show much better
performance than the other methods. The <code>format</code> function that
constructs <code>std::string</code> is even 30% faster than the system's version
of <code>sprintf</code> that uses stack-allocated <code>char</code> buffer.
<code>format_to</code> with a stack-allocated buffer is ~60% faster than
<code>sprintf</code>.

<h2><a name="BinaryCode">Appendix B: Binary code comparison</a></h2>

In this section we compare per-call binary code size between the reference
implementation that uses techniques described in section <a href="#Footprint">
Binary footprint</a> and standard formatting facilities. All the code snippets
are compiled with clang (Apple LLVM version 9.0.0 clang-900.0.39.2) with
<code>-O3 -DNDEBUG -c -std=c++14</code> and the resulted binaries are
disassembled with <code>objdump -S</code>:

<pre><code>  void consume(const char*);

  void sprintf_test() {
    char buffer[100];
    sprintf(buffer, "The answer is %d.", 42);
    consume(buffer);
  }

  __Z12sprintf_testv:
         0:       55      pushq   %rbp
         1:       48 89 e5        movq    %rsp, %rbp
         4:       53      pushq   %rbx
         5:       48 83 ec 78     subq    $120, %rsp
         9:       48 8b 05 00 00 00 00    movq    (%rip), %rax
        10:       48 8b 00        movq    (%rax), %rax
        13:       48 89 45 f0     movq    %rax, -16(%rbp)
        17:       48 8d 35 37 00 00 00    leaq    55(%rip), %rsi
        1e:       48 8d 5d 80     leaq    -128(%rbp), %rbx
        22:       ba 2a 00 00 00  movl    $42, %edx
        27:       31 c0   xorl    %eax, %eax
        29:       48 89 df        movq    %rbx, %rdi
        2c:       e8 00 00 00 00  callq   0 <__Z12sprintf_testv+0x31>
        31:       48 89 df        movq    %rbx, %rdi
        34:       e8 00 00 00 00  callq   0 <__Z12sprintf_testv+0x39>
        39:       48 8b 05 00 00 00 00    movq    (%rip), %rax
        40:       48 8b 00        movq    (%rax), %rax
        43:       48 3b 45 f0     cmpq    -16(%rbp), %rax
        47:       75 07   jne     7 <__Z12sprintf_testv+0x50>
        49:       48 83 c4 78     addq    $120, %rsp
        4d:       5b      popq    %rbx
        4e:       5d      popq    %rbp
        4f:       c3      retq
        50:       e8 00 00 00 00  callq   0 <__Z12sprintf_testv+0x55>

  void format_test() {
    consume(format("The answer is {}.", 42).c_str());
  }

  __Z11format_testv:
         0:       55      pushq   %rbp
         1:       48 89 e5        movq    %rsp, %rbp
         4:       53      pushq   %rbx
         5:       48 83 ec 28     subq    $40, %rsp
         9:       48 c7 45 d0 2a 00 00 00         movq    $42, -48(%rbp)
        11:       48 8d 35 f4 83 01 00    leaq    99316(%rip), %rsi
        18:       48 8d 7d e0     leaq    -32(%rbp), %rdi
        1c:       4c 8d 45 d0     leaq    -48(%rbp), %r8
        20:       ba 11 00 00 00  movl    $17, %edx
        25:       b9 02 00 00 00  movl    $2, %ecx
        2a:       e8 00 00 00 00  callq   0 <__Z11format_testv+0x2F>
        2f:       f6 45 e0 01     testb   $1, -32(%rbp)
        33:       48 8d 7d e1     leaq    -31(%rbp), %rdi
        37:       48 0f 45 7d f0  cmovneq -16(%rbp), %rdi
        3c:       e8 00 00 00 00  callq   0 <__Z11format_testv+0x41>
        41:       f6 45 e0 01     testb   $1, -32(%rbp)
        45:       74 09   je      9 <__Z11format_testv+0x50>
        47:       48 8b 7d f0     movq    -16(%rbp), %rdi
        4b:       e8 00 00 00 00  callq   0 <__Z11format_testv+0x50>
        50:       48 83 c4 28     addq    $40, %rsp
        54:       5b      popq    %rbx
        55:       5d      popq    %rbp
        56:       c3      retq
        57:       48 89 c3        movq    %rax, %rbx
        5a:       f6 45 e0 01     testb   $1, -32(%rbp)
        5e:       74 09   je      9 <__Z11format_testv+0x69>
        60:       48 8b 7d f0     movq    -16(%rbp), %rdi
        64:       e8 00 00 00 00  callq   0 <__Z11format_testv+0x69>
        69:       48 89 df        movq    %rbx, %rdi
        6c:       e8 00 00 00 00  callq   0 <__Z11format_testv+0x71>
        71:       66 66 66 66 66 66 2e 0f 1f 84 00 00 00 00 00    nopw    %cs:(%rax,%rax)

  void ostringstream_test() {
    std::ostringstream ss;
    ss &lt;&lt; "The answer is " &lt;&lt; 42 &lt;&lt; ".";
    consume(ss.str().c_str());
  }

  __Z18ostringstream_testv:
         0:	55 	pushq	%rbp
         1:	48 89 e5 	movq	%rsp, %rbp
         4:	41 57 	pushq	%r15
         6:	41 56 	pushq	%r14
         8:	41 55 	pushq	%r13
         a:	41 54 	pushq	%r12
         c:	53 	pushq	%rbx
         d:	48 81 ec 38 01 00 00 	subq	$312, %rsp
        14:	4c 8d b5 18 ff ff ff 	leaq	-232(%rbp), %r14
        1b:	4c 8d a5 b0 fe ff ff 	leaq	-336(%rbp), %r12
        22:	48 8b 05 00 00 00 00 	movq	(%rip), %rax
        29:	48 8d 48 18 	leaq	24(%rax), %rcx
        2d:	48 89 8d a8 fe ff ff 	movq	%rcx, -344(%rbp)
        34:	48 83 c0 40 	addq	$64, %rax
        38:	48 89 85 18 ff ff ff 	movq	%rax, -232(%rbp)
        3f:	4c 89 f7 	movq	%r14, %rdi
        42:	4c 89 e6 	movq	%r12, %rsi
        45:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x4A>
        4a:	48 c7 45 a0 00 00 00 00 	movq	$0, -96(%rbp)
        52:	c7 45 a8 ff ff ff ff 	movl	$4294967295, -88(%rbp)
        59:	48 8b 1d 00 00 00 00 	movq	(%rip), %rbx
        60:	4c 8d 6b 18 	leaq	24(%rbx), %r13
        64:	4c 89 ad a8 fe ff ff 	movq	%r13, -344(%rbp)
        6b:	48 83 c3 40 	addq	$64, %rbx
        6f:	48 89 9d 18 ff ff ff 	movq	%rbx, -232(%rbp)
        76:	4c 89 e7 	movq	%r12, %rdi
        79:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x7E>
        7e:	4c 8b 3d 00 00 00 00 	movq	(%rip), %r15
        85:	49 83 c7 10 	addq	$16, %r15
        89:	4c 89 bd b0 fe ff ff 	movq	%r15, -336(%rbp)
        90:	48 c7 85 08 ff ff ff 00 00 00 00 	movq	$0, -248(%rbp)
        9b:	48 c7 85 00 ff ff ff 00 00 00 00 	movq	$0, -256(%rbp)
        a6:	48 c7 85 f8 fe ff ff 00 00 00 00 	movq	$0, -264(%rbp)
        b1:	48 c7 85 f0 fe ff ff 00 00 00 00 	movq	$0, -272(%rbp)
        bc:	c7 85 10 ff ff ff 10 00 00 00 	movl	$16, -240(%rbp)
        c6:	0f 57 c0 	xorps	%xmm0, %xmm0
        c9:	0f 29 45 b0 	movaps	%xmm0, -80(%rbp)
        cd:	48 c7 45 c0 00 00 00 00 	movq	$0, -64(%rbp)
        d5:	48 8d 75 b0 	leaq	-80(%rbp), %rsi
        d9:	4c 89 e7 	movq	%r12, %rdi
        dc:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0xE1>
        e1:	f6 45 b0 01 	testb	$1, -80(%rbp)
        e5:	74 09 	je	9 <__Z18ostringstream_testv+0xF0>
        e7:	48 8b 7d c0 	movq	-64(%rbp), %rdi
        eb:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0xF0>
        f0:	48 8d 35 dd 10 00 00 	leaq	4317(%rip), %rsi
        f7:	48 8d bd a8 fe ff ff 	leaq	-344(%rbp), %rdi
        fe:	ba 0e 00 00 00 	movl	$14, %edx
       103:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x108>
       108:	be 2a 00 00 00 	movl	$42, %esi
       10d:	48 89 c7 	movq	%rax, %rdi
       110:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x115>
       115:	48 8d 35 c7 10 00 00 	leaq	4295(%rip), %rsi
       11c:	ba 01 00 00 00 	movl	$1, %edx
       121:	48 89 c7 	movq	%rax, %rdi
       124:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x129>
       129:	48 8d 7d b0 	leaq	-80(%rbp), %rdi
       12d:	4c 89 e6 	movq	%r12, %rsi
       130:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x135>
       135:	f6 45 b0 01 	testb	$1, -80(%rbp)
       139:	48 8d 7d b1 	leaq	-79(%rbp), %rdi
       13d:	48 0f 45 7d c0 	cmovneq	-64(%rbp), %rdi
       142:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x147>
       147:	f6 45 b0 01 	testb	$1, -80(%rbp)
       14b:	74 09 	je	9 <__Z18ostringstream_testv+0x156>
       14d:	48 8b 7d c0 	movq	-64(%rbp), %rdi
       151:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x156>
       156:	4c 89 ad a8 fe ff ff 	movq	%r13, -344(%rbp)
       15d:	48 89 9d 18 ff ff ff 	movq	%rbx, -232(%rbp)
       164:	4c 89 bd b0 fe ff ff 	movq	%r15, -336(%rbp)
       16b:	f6 85 f0 fe ff ff 01 	testb	$1, -272(%rbp)
       172:	74 0c 	je	12 <__Z18ostringstream_testv+0x180>
       174:	48 8b bd 00 ff ff ff 	movq	-256(%rbp), %rdi
       17b:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x180>
       180:	4c 89 e7 	movq	%r12, %rdi
       183:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x188>
       188:	48 8b 35 00 00 00 00 	movq	(%rip), %rsi
       18f:	48 83 c6 08 	addq	$8, %rsi
       193:	48 8d bd a8 fe ff ff 	leaq	-344(%rbp), %rdi
       19a:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x19F>
       19f:	4c 89 f7 	movq	%r14, %rdi
       1a2:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x1A7>
       1a7:	48 81 c4 38 01 00 00 	addq	$312, %rsp
       1ae:	5b 	popq	%rbx
       1af:	41 5c 	popq	%r12
       1b1:	41 5d 	popq	%r13
       1b3:	41 5e 	popq	%r14
       1b5:	41 5f 	popq	%r15
       1b7:	5d 	popq	%rbp
       1b8:	c3 	retq
       1b9:	48 89 45 d0 	movq	%rax, -48(%rbp)
       1bd:	f6 45 b0 01 	testb	$1, -80(%rbp)
       1c1:	74 3b 	je	59 <__Z18ostringstream_testv+0x1FE>
       1c3:	48 8b 7d c0 	movq	-64(%rbp), %rdi
       1c7:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x1CC>
       1cc:	eb 30 	jmp	48 <__Z18ostringstream_testv+0x1FE>
       1ce:	eb 2a 	jmp	42 <__Z18ostringstream_testv+0x1FA>
       1d0:	48 89 45 d0 	movq	%rax, -48(%rbp)
       1d4:	f6 45 b0 01 	testb	$1, -80(%rbp)
       1d8:	74 39 	je	57 <__Z18ostringstream_testv+0x213>
       1da:	48 8b 7d c0 	movq	-64(%rbp), %rdi
       1de:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x1E3>
       1e3:	f6 85 f0 fe ff ff 01 	testb	$1, -272(%rbp)
       1ea:	75 30 	jne	48 <__Z18ostringstream_testv+0x21C>
       1ec:	eb 3a 	jmp	58 <__Z18ostringstream_testv+0x228>
       1ee:	48 89 45 d0 	movq	%rax, -48(%rbp)
       1f2:	eb 3c 	jmp	60 <__Z18ostringstream_testv+0x230>
       1f4:	48 89 45 d0 	movq	%rax, -48(%rbp)
       1f8:	eb 4d 	jmp	77 <__Z18ostringstream_testv+0x247>
       1fa:	48 89 45 d0 	movq	%rax, -48(%rbp)
       1fe:	4c 89 ad a8 fe ff ff 	movq	%r13, -344(%rbp)
       205:	48 89 9d 18 ff ff ff 	movq	%rbx, -232(%rbp)
       20c:	4c 89 bd b0 fe ff ff 	movq	%r15, -336(%rbp)
       213:	f6 85 f0 fe ff ff 01 	testb	$1, -272(%rbp)
       21a:	74 0c 	je	12 <__Z18ostringstream_testv+0x228>
       21c:	48 8b bd 00 ff ff ff 	movq	-256(%rbp), %rdi
       223:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x228>
       228:	4c 89 e7 	movq	%r12, %rdi
       22b:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x230>
       230:	48 8b 35 00 00 00 00 	movq	(%rip), %rsi
       237:	48 83 c6 08 	addq	$8, %rsi
       23b:	48 8d bd a8 fe ff ff 	leaq	-344(%rbp), %rdi
       242:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x247>
       247:	4c 89 f7 	movq	%r14, %rdi
       24a:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x24F>
       24f:	48 8b 7d d0 	movq	-48(%rbp), %rdi
       253:	e8 00 00 00 00 	callq	0 <__Z18ostringstream_testv+0x258>
       258:	0f 1f 84 00 00 00 00 00 	nopl	(%rax,%rax)</code></pre>

<p>
The code generated for the <code>format_test</code> function that uses the
reference implementation of the <code>format</code> function described in
this proposal is several times smaller than the <code>ostringstream</code> code
and only 40% larger than the one generated for <code>sprintf</code> which is a
moderate price to pay for full type and memory safety.
</p>
<p>
The following factors contribute to the difference in binary code size between
<code>format</code> and <code>sprintf</code>:
<ul>
  <li>Passing format string as <code>string_view</code> instead of <code>const
      char*</code>.
  <li>Using <code>string</code> instead of a <code>char</code> buffer.
  <li>Preparing the array of formatting arguments.
</ul>
We can exclude the first two factors from the experiment by mimicking parts of
the <code>sprintf</code> API:

<pre><code>int vraw_format(char* buffer, const char* format, format_args args);

template&lt;typename... Args&gt;
inline int raw_format(char* buffer, const char* format, const Args&amp;... args) {
  return vraw_format(buffer, format, make_format_args(args...));
}

void raw_format_test() {
  char buffer[100];
  raw_format(buffer, "The answer is {}.", 42);
}

__Z15raw_format_testv:
       0:       55      pushq   %rbp
       1:       48 89 e5        movq    %rsp, %rbp
       4:       48 81 ec 80 00 00 00    subq    $128, %rsp
       b:       48 8b 05 00 00 00 00    movq    (%rip), %rax
      12:       48 8b 00        movq    (%rax), %rax
      15:       48 89 45 f8     movq    %rax, -8(%rbp)
      19:       48 c7 45 80 2a 00 00 00         movq    $42, -128(%rbp)
      21:       48 8d 35 24 12 00 00    leaq    4644(%rip), %rsi
      28:       48 8d 7d 90     leaq    -112(%rbp), %rdi
      2c:       48 8d 4d 80     leaq    -128(%rbp), %rcx
      30:       ba 02 00 00 00  movl    $2, %edx
      35:       e8 00 00 00 00  callq   0 <__Z15raw_format_testv+0x3A>
      3a:       48 8b 05 00 00 00 00    movq    (%rip), %rax
      41:       48 8b 00        movq    (%rax), %rax
      44:       48 3b 45 f8     cmpq    -8(%rbp), %rax
      48:       75 09   jne     9 <__Z15raw_format_testv+0x53>
      4a:       48 81 c4 80 00 00 00    addq    $128, %rsp
      51:       5d      popq    %rbp
      52:       c3      retq
      53:       e8 00 00 00 00  callq   0 <__Z15raw_format_testv+0x58>
      58:       0f 1f 84 00 00 00 00 00         nopl    (%rax,%rax)</code></pre>

This shows that passing formatting arguments adds very little overhead and
is comparable with <code>sprintf</code>.
</div>
</body>
