<!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: P0645R2<br>
Audience: Library Evolution, Library<br>
Author: <a href="mailto:victor.zverovich@gmail.com">Victor Zverovich</a><br>
<br>
2018-04-28
</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/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 the <a href="#SyntaxRef">syntax reference</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 <>
  struct formatter&lt;tm&gt; {
    constexpr parse_context::iterator parse(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, 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;, parse_context&amp; ctx);
</code></pre>
</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="http://open-std.org/JTC1/SC22/WG21/docs/papers/2015/n4412.html">
N4412: Shortcomings of iostreams</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>

<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="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>

Add a new section in 23 [utilities].

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

<!-- Synopsis example: http://eel.is/c%2B%2Bdraft/time#syn
     Code check: https://godbolt.org/g/BvhYXx -->
<h4>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_parse_context;
  using parse_context = basic_parse_context&lt;char&gt;;
  using wparse_context = basic_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 OutputIterator, class charT&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(Visitor&amp;&amp; vis, basic_format_arg&lt;Context&gt; arg);

  template &lt;class Context, class... Args&gt; using format_arg_store = <i>unspecified</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 OutputIterator, class charT&gt;
    using format_args_t = basic_format_args&lt;basic_format_context&lt;OutputIterator, charT&gt;&gt;;

  template &lt;class 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;format_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;class OutputIterator, class... Args&gt;
    OutputIterator format_to(OutputIterator out, string_view fmt,
                             const Args&amp;... args);
  template &lt;class OutputIterator, class... Args&gt;
    OutputIterator format_to(OutputIterator out, wstring_view fmt,
                             const Args&amp;... args);

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

  template &lt;class OutputIterator, class Size&gt;
    struct format_to_n_result {
      OutputIterator out;
      Size 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;class OutputIterator, class Size, class... Args&gt;
    format_to_n_result&lt;OutputIterator, Size&gt;
      format_to_n(OutputIterator out, Size n, string_view fmt,
                  const Args&amp;... args);
  template &lt;class OutputIterator, class Size, class... Args&gt;
    format_to_n_result&lt;OutputIterator, Size&gt;
      format_to_n(OutputIterator out, Size 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="SyntaxRef">Format string syntax [format.syntax]</a></h4>

<p>
Format strings contain <em>replacement fields</em> surrounded by curly braces
<code>{}</code>. Anything that is not contained in braces is considered literal
text, which is copied unchanged to the output. A brace character can be
included in the literal text by doubling: <code>{{</code> and <code>}}</code>.
</p>

<p>
The grammar for a replacement field is as follows:
</p>

<!-- 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            ::=  integer
integer           ::=  digit+
digit             ::=  '0'...'9'</code>
</pre>

<p>
In less formal terms, the replacement field can start with an
<code>arg-id</code> that specifies the argument whose value is to be formatted
and inserted into the output instead of the replacement field. The
<code>arg-id</code> is optionally followed by a <code>format-spec</code>,
which is preceded by a colon <code>':'</code>. These specify a non-default
format for the replacement value.
</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>
Format string examples:
</p>

<pre class="example">
<code>"First, thou shalt count to {0}" // References the first argument
"Bring me a {}"                  // Implicitly references the first argument
"From {} to {}"                  // Same as "From {0} to {1}"
"From {0} to {}"                 // Error: mixing automatic and manual indexing
"From {} to {1}"                 // Error: mixing automatic and manual indexing</code>
</pre>

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

<p>
Most built-in types support a common formatting mini-language, which is
described in the <a href="#FormatSpec">next section</a>.
</p>

<p>
A <code>format-spec</code> field can also include nested replacement fields
in certain positions within it. These nested replacement fields can contain only
an argument index - format specifications are not allowed. This allows the
formatting of a value to be dynamically specified.
</p>

<h5><a name="FormatSpec">Format specification mini-language</a></h5>

<p>
<em>Format specifications</em> are used within replacement fields contained
within a format string to define how individual values are presented (see
<a href="#SyntaxRef">Format string syntax</a>). Each formattable type may define
how the format specification is to be interpreted.
</p>

<p>
Most built-in types implement the following options for format specifications,
although some of the formatting options are only supported by arithmetic types.
</p>

<p>
The general form of a <em>standard format specifier</em> is:
</p>

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

<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>
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).</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).</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.</td>
</tr>
<tr>
<td><code>'^'</code></td>
<td>Forces the field to be centered within the available space.</td>
</tr>
</tbody>
</table>

<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, and 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>'#'</code> option causes the <em>alternate form</em> to be used for
the conversion.
This option is only valid for integer and floating-point types. 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> is a decimal number indicating how many digits should
be displayed after the decimal point for a floating-point value formatted with
<code>'f'</code> and <code>'F'</code>, or before and after the decimal point
for a floating-point value formatted with <code>'g'</code> or <code>'G'</code>.
For non-arithmetic types the field indicates the maximum field size - in other
words, how many characters will be used from the field content. The
<code>precision</code> is not allowed for integer, character, boolean, and
pointer values.
</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>String format. This is the default type for strings and may be omitted.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'s'</code>.</td>
</tr>
</tbody>
</table>

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

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'c'</code></td>
<td>Character format. This is the default type for characters and may be
    omitted.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'c'</code>.</td>
</tr>
</tbody>
</table>

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

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'b'</code></td>
<td>Binary format. Outputs the number in base 2. Using the <code>'#'</code>
    option with this type adds the prefix <code>"0b"</code> to the output
    value.</td>
</tr>
<tr>
<td><code>'B'</code></td>
<td>Binary format. Outputs the number in base 2. Using the <code>'#'</code>
    option with this type adds the prefix <code>"0B"</code> to the output
    value.</td>
</tr>
<tr>
<td><code>'d'</code></td>
<td>Decimal integer. Outputs the number in base 10.</td>
</tr>
<tr>
<td><code>'o'</code></td>
<td>Octal format. Outputs the number in base 8. Using the '#' option with this
    type adds the prefix "0" to the output value.</td>
</tr>
<tr>
<td><code>'x'</code></td>
<td>Hex format. Outputs the number in base 16, using lower-case letters for the
    digits above 9. Using the <code>'#'</code> option with this type adds the
    prefix <code>"0x"</code> to the output value.</td>
</tr>
<tr>
<td><code>'X'</code></td>
<td>Hex format. Outputs the number in base 16, using upper-case letters for the
    digits above 9. Using the <code>'#'</code> option with this type adds the
    prefix <code>"0X"</code> to the output value.</td>
</tr>
<tr>
<td><code>'n'</code></td>
<td>Number. This is the same as <code>'d'</code> except that it uses the
    current locale to insert the appropriate number separator characters.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'d'</code>.</td>
</tr>
</tbody>
</table>

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

<p>The available presentation types for floating-point values are:</p>

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'a'</code></td>
<td>Hexadecimal floating point format. Prints the number in base 16 with prefix
    <code>"0x"</code> and lower-case letters for digits above 9. Uses
    <code>'p'</code> to indicate the exponent.</td>
</tr>
<tr>
<td><code>'A'</code></td>
<td>Same as <code>'a'</code> except it uses upper-case letters for the prefix,
    digits above 9 and to indicate the exponent.</td>
</tr>
<tr>
<td><code>'e'</code></td>
<td>Exponent notation. Prints the number in scientific notation using the
    letter <code>'e'</code> to indicate the exponent.</td>
</tr>
<tr>
<td><code>'E'</code></td>
<td>Exponent notation. Same as <code>'e'</code> except it uses an upper-case
    <code>'E'</code> as the separator character.</td>
</tr>
<tr>
<td><code>'f'</code></td>
<td>Fixed point. Displays the number as a fixed-point number.</td>
</tr>
<tr>
<td><code>'F'</code></td>
<td>Fixed point. Same as <code>'f'</code>, but converts <code>nan</code> to
    <code>NAN</code> and <code>inf</code> to <code>INF</code>.</td>
</tr>
<tr>
<td><code>'g'</code></td>
<td>General format. For a given precision <code>p >= 1</code>, this rounds the
    number to <code>p</code> significant digits and then formats the result in
    either fixed-point format or in scientific notation, depending on its
    magnitude.

    A precision of <code>0</code> is treated as equivalent to a precision of
    <code>1</code>.</td>
</tr>
<tr>
<td><code>'G'</code></td>
<td>General format. Same as <code>'g'</code> except switches to <code>'E'</code>
    if the number gets too large. The representations of infinity and NaN are
    uppercased, too.</td>
</tr>
<tr>
<td><code>'n'</code></td>
<td>Number. This is the same as <code>'g'</code>, except that it uses the
    locale to insert the appropriate number separator characters.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'g'</code>.</td>
</tr>
</tbody>
</table>

<p>The available presentation types for pointers are:</p>

<table>
<thead>
<tr><th>Type</th><th>Meaning</th></tr>
</thead>
<tbody>
<tr>
<td><code>'p'</code></td>
<td>Pointer format. This is the default type for pointers and may be
    omitted.</td>
</tr>
<tr>
<td>none</td>
<td>The same as <code>'p'</code>.</td>
</tr>
</tbody>
</table>

<h4><a name="format.error">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>Effects</i>: Constructs an object of class <code>format_error</code>.
  </p>
  <p><i>Postconditions</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>Effects</i>: Constructs an object of class <code>format_error</code>.
  </p>
  <p><i>Postconditions</i>: <code>strcmp(what(), what_arg) == 0</code>.</p>
</dd>
</dl>

<h4><a name="format.arguments">Arguments [format.arguments]</a></h4>
<h5>Class template <code>basic_format_arg</code></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;

    basic_format_arg();

    explicit operator bool() const noexcept;

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

<!-- Wording is similar to http://www.eel.is/c++draft/string.view -->
<p>
The class template <code>basic_format_arg</code> describes an object that can
refer to a formatting function argument. It is parameterized on a formatting
context type (see <a href="#format.formatter">[format.formatter]</a>) and
can hold a value of one of the following types:
<ul>
<li><code>bool</code>
<li><code>charT</code>
<li>any integral type other than <code>bool</code> and <code>charT</code>
<li>any floating-point type
<li><code>const charT*</code>
<li><code>basic_string_view&lt;charT&gt;</code>
<li><code>const void*</code>
<li><code>basic_format_arg::handle</code> referring to an argument of a
    user-defined type <code>T</code> with an enabled specialization of
    <code>formatter&lt;T&gt;</code>
<li><code>monostate</code> representing an empty state, i.e. when the
    object does not refer to an argument
</ul>
where <code>charT</code> is <code>typename Context::char_type</code>.
The value can be accessed via the visitation interface defined in the next
section. <code>basic_format_arg</code> must preserve argument values, but
does not have to distinguish between integral types other than <code>charT</code>
and <code>bool</code>, e.g. an argument of type <code>short</code> can be stored
as <code>int</code> and observed as <code>int</code> via the visitation
interface. Similarly, <code>basic_format_arg</code> does not have to distinguish
between floating-point types. 
</p>

<dl>
<dt><code>basic_format_arg();</code></dt>
<dd>
<p><i>Effects</i>: Constructs a <code>basic_format_arg</code> object that
doesn't refer to an argument.
</p>
<p><i>Postconditions</i>: <code>!(*this)</code>.</p>
</dd>
<dt><code>explicit operator bool() const noexcept;</code></dt>
<dd>
<p><i>Returns</i>: <code>true</code> if and only if <code>*this</code> refers to
an argument.</p>
</dd>
<dt><code>bool is_arithmetic() const;</code></dt>
<dd>
<p><i>Returns</i>: <code>true</code> if and only if <code>*this</code> refers to
an argument of an arithmetic type.</p>
</dd>
<dt><code>bool is_integral() const;</code></dt>
<dd>
<p><i>Returns</i>: <code>true</code> if and only if <code>*this</code> refers to
an argument of an integral type.</p>
</dd>
</dl>

<!-- 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 {
  public:
    void format(Context&amp; ctx) const;
  };
}</code>
</pre>

<p>
The class <code>handle</code> describes an object that can refer to a formatting
function argument of a user-defined type.
</p>

<dl>
<dt><code>void format(Context&amp; ctx) const;</code></dt>
<dd>
<!-- Similar effects example: http://eel.is/c%2B%2Bdraft/time.format -->
<p><i>Effects</i>:
Constructs a local variable of type 
<code>typename Context::template formatter_type&lt;T&gt;</code> (named
<code>f</code> for exposition purposes), where <code>T</code> is the type of the
object <code>obj</code> referred to by this handle. Executes
<code>ctx.parse_context().advance_to(f.parse(ctx.parse_context()))</code>.
Then calls <code>ctx.advance_to(f.format(obj, ctx))</code>.
</ol>
</p>
</dd>

<h5>Argument visitation</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(Visitor&amp;&amp; vis, basic_format_arg&lt;Context&gt; arg);</code></pre></dt>
<dd>
<p><i>Requires:</i>
The expression in the Effects section shall be a valid expression of the same
type, for all alternative value types of a formatting argument.
Otherwise, the program is ill-formed.</p>
<p><i>Effects:</i>
Let <code>value</code> be the value stored in <code>arg</code>.
Returns <code>INVOKE(std::forward<Visitor>(vis), value);</code>.</p>
<p><i>Remarks:</i>
The return type is the common type of all possible <code>INVOKE</code>
expressions in the Effects section. Since exact value types are
implementation-defined, visitors should use type traits to handle multiple
types.
</p>
<!-- Formatting example: http://eel.is/c%2B%2Bdraft/time.duration.cons
     Compilation test: https://godbolt.org/g/ueEgXX -->
<p>[ <i>Example:</i><pre>
<code>  auto uint_value = visit([](auto value) -&gt; unsigned {
    if constexpr (std::is_unsigned_v&lt;decltype(value)&gt;)
      return value;
    return 0;
  }, arg);</code>
</pre> — <i>end example</i> ]
</dd>
</dl>

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

<pre>
<code>namespace std {
  template &lt;class Context&gt;
  class basic_format_args {
  public:
    using size_type = size_t;

    basic_format_args() noexcept;

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

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

<!-- Wording is similar to http://eel.is/c++draft/initializer_list.syn -->
<p>
An object of type <code>basic_format_args</code> provides access to formatting
arguments. Copying a <code>basic_format_args</code> object does not copy the
arguments.
</p>

<dl>
<dt><code>basic_format_args() noexcept;</code></dt>
<dd>
<p><i>Effects</i>: Constructs an empty <code>basic_format_args</code> object.
</p>
<p><i>Postconditions</i>: <code>!get(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);</code></pre></dt>
<dd>
<p><i>Effects</i>: Constructs a <code>basic_format_args</code> object that
provides access to the arguments captured in <code>store</code>.
</p>
</dd>
</dl>

<dl>
<dt><code>basic_format_arg&lt;Context&gt; get(size_type i) const;</code></dt>
<dd>
<p><i>Returns</i>: A <code>basic_format_arg</code> object that represents an
argument at index <code>i</code> if <code>i &lt;</code> the number of arguments.
Otherwise, returns an empty <code>basic_format_arg</code> object.</p>
</dd>
</dl>

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

<dl>
<dt>
<pre><code>template &lt;class 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;format_context, Args...&gt; make_format_args(const Args&amp;... args);</code></pre>
</dt>
<dd>

<p>
<i>Effects</i>: The function returns a <code>format_arg_store</code> object
that refers to formatting arguments <code>args</code>.
</p>
</dd>
</dl>

<h5>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>Effects</i>: The function returns a <code>format_arg_store</code> object
that refers to formatting arguments <code>args</code>.
</p>
</dd>
</dl>

<h4><a name="format.functions">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>
<i>Effects</i>: The function returns a <code>string</code> object
constructed from the format string argument <code>fmt</code> with each
replacement field substituted with the character representation of the
argument it refers to, formatted according to the specification given in the
field.
</p>
<p><i>Returns</i>: The formatted string.</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 OutputIterator, class... Args&gt;
  OutputIterator format_to(OutputIterator out, string_view fmt,
                           const Args&amp;... args);</code></pre>
</dt>
<dd>
<p><i>Returns</i>: <code>vformat_to(out, fmt, make_format_args(args...))</code>.</p>
</dd>
</dl>

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

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

<p>
<i>Effects</i>: The function writes to the range <code>[out, out + size)</code>,
where <code>size</code> is the output size, the format string <code>fmt
</code> with each replacement field substituted with the character
representation of the argument it refers to, formatted according to the
specification given in the field.
</p>
<p><i>Returns</i>: The end of the output range.</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 OutputIterator, class Size, class... Args&gt;
  format_to_n_result&lt;OutputIterator, Size&gt;
    format_to_n(OutputIterator out, Size n, string_view fmt,
                const Args&amp;... args);
template &lt;class OutputIterator, class Size, class... Args&gt;
  format_to_n_result&lt;OutputIterator, Size&gt;
    format_to_n(OutputIterator out, Size n, wstring_view fmt,
                const Args&amp;... args);</code></pre>
</dt>
<dd>

<p>
<i>Effects</i>: The function writes to the range <code>[out, out + n)</code>
the format string <code>fmt</code> with each replacement field substituted
with the character representation of the argument it refers to, formatted
according to the specification given in the field.
</p>
<p><i>Returns</i>: <code>format_to_n_result</code> containing the end of the
output range and the total (not truncated) output size.</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>Effects</i>: The function returns the number of characters in the output of
<code>format(fmt, args...)</code> without constructing the formatted
string.
</p>
<p><i>Returns</i>: The number of characters in the output of
<code>format(fmt, args...)</code>.
</p>
<p><i>Throws</i>: <code>format_error</code> if <code>fmt</code> is not a
valid format string.</p>
</dd>
</dl>

<h4><a name="format.formatter">Formatter [format.formatter]</a></h4>
<h5>Class template <code>basic_parse_context</code></h5>

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

    explicit constexpr basic_parse_context(basic_string_view&lt;charT&gt; fmt);

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

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

<p>
The class template <code>basic_parse_context</code> provides access 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_parse_context(basic_string_view&lt;charT&gt;	fmt);</code></dt>
<dd>
<p><i>Effects</i>: Constructs a parsing context from the format string
<code>fmt</code>.</p>
<p><i>Postconditions</i>: <code>begin() == fmt.begin()</code>,
<code>end() == fmt.end()</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>: An iterator referring to the first character in the format
string range being parsed.</p>
</dd>
<dt><code>constexpr const_iterator end() const noexcept;</code></dt>
<dd>
<p><i>Returns</i>: An iterator referring to the position one past the last
character in the format string range being parsed.</p>
</dd>
<dt><code>void advance_to(iterator it);</code></dt>
<dd>
<p><i>Effects</i>: Advances the beginning of the parsed format string range to
<code>it</code>.</p>
<p><i>Requires</i>: <code>end()</code> shall be reachable from <code>it</code>.
<p><i>Postconditions</i>: <code>begin() == it</code>.</p>
</dd>
<dt><code>constexpr size_t next_arg_id();</code></dt>
<dd>
<p><i>Returns</i>: The next argument identifier starting from 0. Each subsequent
call to <code>next_arg_id</code> gives an identifier which is 1 greater than the
one returned from the previous call for the same context object.</p>
<p><i>Throws</i>: <code>format_error</code> if <code>check_arg_id</code>
has been called earlier 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>Throws</i>: <code>format_error</code> if <code>next_arg_id</code>
has been called earlier which indicates mixing of automatic and manual
argument indexing.</p>
</dd>
</dl>

<h5>Class template <code>basic_format_context</code></h5>

<!-- Code check: https://godbolt.org/g/8xNnUy -->
<pre>
<code>namespace std {
  template &lt;class OutputIterator, class charT&gt;
  class basic_format_context {
  public:
    using iterator = OutputIterator;
    using char_type = charT;
    using args_type = basic_format_args&lt;basic_format_context&gt;;

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

    basic_parse_context&lt;charT&gt;&amp; parse_context();

    iterator out();
    void advance_to(iterator it);

    args_type args() const;
  };
}</code>
</pre>

<p>
The class template <code>basic_format_context</code> provides access to format
string parsing context, output iterator and formatting arguments.
</p>

<dl>
<dt><code>basic_parse_context&lt;charT&gt;&amp; parse_context();</code></dt>
<dd>
<p><i>Returns</i>: A reference to the format string parsing context.</p>
</dd>
<dt><code>iterator out();</code></dt>
<dd>
<p><i>Returns</i>: An iterator referring to the current position in the output
range.</p>
</dd>
<dt><code>void advance_to(iterator it);</code></dt>
<dd>
<p><i>Effects</i>: Advances the current position in the output range to
<code>it</code>.</p>
<p><i>Postconditions</i>: <code>out() == it</code>.</p>
</dd>
<dt><code>args_type args() const;</code></dt>
<dd>
<p><i>Returns</i>: A copy of the <code>args_type</code> object that provides
access to formatting arguments.</p>
</dd>
</dl>

<h5>Class template <code>formatter</code></h5>

<!-- 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
<code>Formatter</code> requirements, and disabled specializations do not.
<i>— end note</i> ] Each header that declares the template <code>formatter</code>
provides enabled specializations <code>formatter&lt;const char*, char&gt;</code>,
<code>formatter&lt;const wchar_t*, wchar_t&gt;</code> as well as
specialiazations of <code>formatter</code> for <code>nullptr_t</code>,
<code>const void*</code>, and all cv-unqualified arithmetic types. For any type
<code>T</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&gt;</code> is disabled.
</p>

<p>
If the library provides an explicit or partial specialization of
<code>formatter&lt;T&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&gt;</code> will satisfy the
<code>Formatter</code> requirements (Table 1), with <code>T</code> as the
formatted argument type, the <code>DefaultConstructible</code> requirements, and
the <code>CopyAssignable</code> requirements.
</p>

<h5>Formatter requirements</h5>

<!-- Based on http://eel.is/c++draft/hash.requirements -->
<p>
A type <code>F</code> meets the <code>Formatter</code> requirements if:
<ul class="itemize">
<li>it satisfies the <code>CopyConstructible</code> and
    <code>Destructible</code>  requirements, and
<li>the expressions shown in Table 1 are valid and have the indicated
    semantics.
</ul>
</p>

<p>
Given character type <code>charT</code>, output iterator type
<code>OutputIterator</code>, and formatted 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_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;OutputIterator, 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 — <code>Formatter</code> 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>


<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 Beman Dawes, Bengt Gustafsson, Eric Niebler, Jason McKesson, Jeffrey
Yasskin, Joël Lamotte, 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 <a name="SyntaxRef">Format string syntax</a> section 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>
</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>
