Files
2025-10-25 03:02:53 +03:00

128 KiB
Raw Permalink Blame History

[format]

28 Text processing library [text]

28.5 Formatting [format]

28.5.1 Header synopsis [format.syn]

🔗

namespace std {// [format.context], class template basic_format_contexttemplate<class Out, class charT> class basic_format_context; using format_context = basic_format_context<unspecified, char>; using wformat_context = basic_format_context<unspecified, wchar_t>; // [format.args], class template basic_format_argstemplate class basic_format_args; using format_args = basic_format_args<format_context>; using wformat_args = basic_format_args<wformat_context>; // [format.fmt.string], class template basic_format_stringtemplate<class charT, class... Args>struct basic_format_string; template struct runtime-format-string { // exposition onlyprivate: basic_string_view str; // exposition onlypublic:runtime-format-string(basic_string_view s) noexcept : str(s) {}runtime-format-string(const runtime-format-string&) = delete; runtime-format-string& operator=(const runtime-format-string&) = delete; }; runtime-format-string runtime_format(string_view fmt) noexcept { return fmt; }runtime-format-string<wchar_t> runtime_format(wstring_view fmt) noexcept { return fmt; }template<class... Args>using format_string = basic_format_string<char, type_identity_t...>; template<class... Args>using wformat_string = basic_format_string<wchar_t, type_identity_t...>; // [format.functions], formatting functionstemplate<class... Args> string format(format_string<Args...> fmt, Args&&... args); template<class... Args> wstring format(wformat_string<Args...> fmt, Args&&... args); template<class... Args> string format(const locale& loc, format_string<Args...> fmt, Args&&... args); template<class... Args> wstring format(const locale& loc, wformat_string<Args...> fmt, Args&&... args);

string vformat(string_view fmt, format_args args); wstring vformat(wstring_view fmt, wformat_args args); string vformat(const locale& loc, string_view fmt, format_args args); wstring vformat(const locale& loc, wstring_view fmt, wformat_args args); template<class Out, class... Args> Out format_to(Out out, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> Out format_to(Out out, wformat_string<Args...> fmt, Args&&... args); template<class Out, class... Args> Out format_to(Out out, const locale& loc, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> Out format_to(Out out, const locale& loc, wformat_string<Args...> fmt, Args&&... args); template Out vformat_to(Out out, string_view fmt, format_args args); template Out vformat_to(Out out, wstring_view fmt, wformat_args args); template Out vformat_to(Out out, const locale& loc, string_view fmt, format_args args); template Out vformat_to(Out out, const locale& loc, wstring_view fmt, wformat_args args); template struct format_to_n_result { Out out; iter_difference_t size; }; template<class Out, class... Args> format_to_n_result format_to_n(Out out, iter_difference_t n, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result format_to_n(Out out, iter_difference_t n, wformat_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result format_to_n(Out out, iter_difference_t n, const locale& loc, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result format_to_n(Out out, iter_difference_t n, const locale& loc, wformat_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(format_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(wformat_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(const locale& loc, format_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(const locale& loc, wformat_string<Args...> fmt, Args&&... args); // [format.formatter], formattertemplate<class T, class charT = char> struct formatter; // [format.formatter.locking], formatter lockingtemplateconstexpr bool enable_nonlocking_formatter_optimization = false; // [format.formattable], concept formattabletemplate<class T, class charT>concept formattable = see below; template<class R, class charT>concept const-formattable-range = // exposition only ranges::input_range &&formattable<ranges::range_reference_t, charT>; template<class R, class charT>using fmt-maybe-const = // exposition only conditional_t<const-formattable-range<R, charT>, const R, R>; // [format.parse.ctx], class template basic_format_parse_contexttemplate class basic_format_parse_context; using format_parse_context = basic_format_parse_context; using wformat_parse_context = basic_format_parse_context<wchar_t>; // [format.range], formatting of ranges// [format.range.fmtkind], variable template format_kindenum class range_format {disabled, map, set, sequence, string, debug_string}; templateconstexpr unspecified format_kind = unspecified; template<ranges::input_range R>requires same_as<R, remove_cvref_t>constexpr range_format format_kind = see below; // [format.range.formatter], class template range_formattertemplate<class T, class charT = char>requires same_as<remove_cvref_t, T> && formattable<T, charT>class range_formatter; // [format.range.fmtdef], class template range-default-formattertemplate<range_format K, ranges::input_range R, class charT>struct range-default-formatter; // exposition only// [format.range.fmtmap], [format.range.fmtset], [format.range.fmtstr], specializations for maps, sets, and stringstemplate<ranges::input_range R, class charT>requires (format_kind != range_format::disabled) &&formattable<ranges::range_reference_t, charT>struct formatter<R, charT> : range-default-formatter<format_kind, R, charT> { }; template<ranges::input_range R>requires (format_kind != range_format::disabled)constexpr bool enable_nonlocking_formatter_optimization = false; // [format.arguments], arguments// [format.arg], class template basic_format_argtemplate class basic_format_arg; // [format.arg.store], class template format-arg-storetemplate<class Context, class... Args> class format-arg-store; // exposition onlytemplateformat-arg-store<Context, Args...> make_format_args(Args&... fmt_args); template<class... Args>format-arg-store<wformat_context, Args...> make_wformat_args(Args&... args); // [format.error], class format_errorclass format_error;}

1

#

The class template format_to_n_result has the template parameters, data members, and special members specified above.

It has no base classes or members other than those specified.

28.5.2 Format string [format.string]

28.5.2.1 General [format.string.general]

1

#

A format string for arguments args is a (possibly empty) sequence ofreplacement fields,escape sequences, and characters other than { and }.

Let charT be the character type of the format string.

Each character that is not part of a replacement field or an escape sequence is copied unchanged to the output.

An escape sequence is one of {{ or }}.

It is replaced with { or }, respectively, in the output.

The syntax of replacement fields is as follows:

replacement-field :
{ arg-idopt format-specifieropt }

arg-id :
0
positive-integer

positive-integer :
nonzero-digit
positive-integer digit

nonnegative-integer :
digit
nonnegative-integer digit

nonzero-digit : one of
1 2 3 4 5 6 7 8 9

digit : one of
0 1 2 3 4 5 6 7 8 9

format-specifier :
format-spec

format-spec :
as specified by the formatter specialization for the argument type; cannot start with }

2

#

The arg-id field specifies the index of the argument in args whose value is to be formatted and inserted into the output instead of the replacement field.

If there is no argument with the index arg-id in args, the string is not a format string for args.

The optional format-specifier field explicitly specifies a format for the replacement value.

3

#

[Example 1: string s = format("{0}-{{", 8); // value of s is "8-{" — end example]

4

#

If all arg-id**s in a format string are omitted (including those in the format-spec, as interpreted by the corresponding formatter specialization), argument indices 0, 1, 2, … will automatically be used in that order.

If some arg-id**s are omitted and some are present, the string is not a format string.

[Note 1:

A format string cannot contain a mixture of automatic and manual indexing.

— end note]

[Example 2: 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"); // not a format string (mixing automatic and manual indexing),// ill-formed string s3 = format("{} to {1}", "a", "b"); // not a format string (mixing automatic and manual indexing),// ill-formed — end example]

5

#

The format-spec field containsformat specifications that define how the value should be presented.

Each type can define its own interpretation of the format-spec field.

If format-spec does not conform to the format specifications for the argument type referred to by arg-id, the string is not a format string for args.

[Example 3:

  • (5.1)

    For arithmetic, pointer, and string types the format-spec is interpreted as a std-format-spec as described in [format.string.std].

  • (5.2)

    For chrono types the format-spec is interpreted as a chrono-format-spec as described in [time.format].

  • (5.3)

    For user-defined formatter specializations, the behavior of the parse member function determines how the format-spec is interpreted.

— end example]

28.5.2.2 Standard format specifiers [format.string.std]

1

#

Each formatter specialization described in [format.formatter.spec] for fundamental and string types interprets format-spec as astd-format-spec.

[Note 1:

The format specification can be used to specify such details as minimum field width, alignment, padding, and decimal precision.

Some of the formatting options are only supported for arithmetic types.

— end note]

The syntax of format specifications is as follows:

std-format-spec :
fill-and-alignopt signopt #opt 0opt widthopt precisionopt Lopt typeopt

fill-and-align :
fillopt align

fill :
any character other than { or }

align : one of
< > ^

sign : one of

    • space

width :
positive-integer
{ arg-idopt }

precision :
. nonnegative-integer
. { arg-idopt }

type : one of
a A b B c d e E f F g G o p P s x X ?

2

#

Field widths are specified in field width units; the number of column positions required to display a sequence of characters in a terminal.

The minimum field width is the number of field width units a replacement field minimally requires of the formatted sequence of characters produced for a format argument.

The estimated field width is the number of field width units that are required for the formatted sequence of characters produced for a format argument independent of the effects of the width option.

The padding width is the greater of 0 and the difference of the minimum field width and the estimated field width.

[Note 2:

The POSIX wcswidth function is an example of a function that, given a string, returns the number of column positions required by a terminal to display the string.

— end note]

3

#

The fill character is the character denoted by the fill option or, if the fill option is absent, the space character.

For a format specification in UTF-8, UTF-16, or UTF-32, the fill character corresponds to a single Unicode scalar value.

[Note 3:

The presence of a fill option is signaled by the character following it, which must be one of the alignment options.

If the second character of std-format-spec is not a valid alignment option, then it is assumed that the fill and align options are both absent.

— end note]

4

#

The align option applies to all argument types.

The meaning of the various alignment options is as specified in Table 104.

[Example 1: char c = 120; string s0 = format("{:6}", 42); // value of s0 is " 42" string s1 = format("{:6}", 'x'); // value of s1 is "x " string s2 = format("{:<6}", 'x'); // value of s2 is "x*****" string s3 = format("{:>6}", 'x'); // value of s3 is "***x" string s4 = format("{:^6}", 'x'); // value of s4 is "x" string s5 = format("{:6d}", c); // value of s5 is " 120" string s6 = format("{:6}", true); // value of s6 is "true " string s7 = format("{:<6.3}", "123456"); // value of s7 is "123" string s8 = format("{:02}", 1234); // value of s8 is "1234" string s9 = format("{:<}", "12"); // value of s9 is "12" string sA = format("{:<6}", "12345678"); // value of sA is "12345678" string sB = format("{:🤡^6}", "x"); // value of sB is "🤡🤡x🤡🤡🤡" string sC = format("{:*^6}", "🤡🤡🤡"); // value of sC is "🤡🤡🤡" — end example]

[Note 4:

The fill, align, and 0 options have no effect when the minimum field width is not greater than the estimated field width because padding width is 0 in that case.

Since fill characters are assumed to have a field width of 1, use of a character with a different field width can produce misaligned output.

The 🤡 (U+1f921 clown face) character has a field width of 2.

The examples above that include that character illustrate the effect of the field width when that character is used as a fill character as opposed to when it is used as a formatting argument.

— end note]

Table 104 — Meaning of align options [tab:format.align]

🔗
Option
Meaning
🔗
<
Forces the formatted argument to be aligned to the start of the field by inserting n fill characters after the formatted argument where n is the padding width.
This is the default for non-arithmetic non-pointer types, charT, and bool, unless an integer presentation type is specified.
🔗
>
Forces the formatted argument to be aligned to the end of the field by inserting n fill characters before the formatted argument where n is the padding width.
This is the default for arithmetic types other than charT and bool, pointer types, or when an integer presentation type is specified.
🔗
^
Forces the formatted argument to be centered within the field by inserting ⌊n2⌋ fill characters before and ⌈n2⌉ fill characters after the formatted argument, where n is the padding width.

5

#

The sign option is only valid for arithmetic types other than charT and bool or when an integer presentation type is specified.

The meaning of the various options is as specified in Table 105.

Table 105 — Meaning of sign options [tab:format.sign]

🔗
Option
Meaning
🔗
+
Indicates that a sign should be used for both non-negative and negative numbers.
The + sign is inserted before the output of to_chars for non-negative numbers other than negative zero.
[Note 5:
For negative numbers and negative zero the output of to_chars will already contain the sign so no additional transformation is performed. — end note]
🔗
-
Indicates that a sign should be used for negative numbers and negative zero only (this is the default behavior).
🔗
space
Indicates that a leading space should be used for non-negative numbers other than negative zero, and a minus sign for negative numbers and negative zero.

6

#

The sign option applies to floating-point infinity and NaN.

[Example 2: double inf = numeric_limits::infinity();double nan = numeric_limits::quiet_NaN(); string s0 = format("{0:},{0:+},{0:-},{0: }", 1); // value of s0 is "1,+1,1, 1" string s1 = format("{0:},{0:+},{0:-},{0: }", -1); // value of s1 is "-1,-1,-1,-1" string s2 = format("{0:},{0:+},{0:-},{0: }", inf); // value of s2 is "inf,+inf,inf, inf" string s3 = format("{0:},{0:+},{0:-},{0: }", nan); // value of s3 is "nan,+nan,nan, nan" — end example]

7

#

The # option causes thealternate form to be used for the conversion.

This option is valid for arithmetic types other thancharT and bool or when an integer presentation type is specified, and not otherwise.

For integral types, the alternate form inserts the base prefix (if any) specified in Table 107 into the output after the sign character (possibly space) if there is one, or before the output of to_chars otherwise.

For floating-point types, the alternate form causes the result of the conversion of finite values 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 g and G conversions, trailing zeros are not removed from the result.

8

#

The 0 option is valid for arithmetic types other than charT and bool, pointer types, or when an integer presentation type is specified.

For formatting arguments that have a value other than an infinity or a NaN, this option pads the formatted argument by inserting the 0 character n times following the sign or base prefix indicators (if any) where n is 0 if the align option is present and is the padding width otherwise.

[Example 3: char c = 120; string s1 = format("{:+06d}", c); // value of s1 is "+00120" string s2 = format("{:#06x}", 0xa); // value of s2 is "0x000a" string s3 = format("{:<06}", -42); // value of s3 is "-42 " (0 has no effect) string s4 = format("{:06}", inf); // value of s4 is " inf" (0 has no effect) — end example]

9

#

The width option specifies the minimum field width.

If the width option is absent, the minimum field width is 0.

10

#

If { arg-idopt } is used in a width or precision option, the value of the corresponding formatting argument is used as the value of the option.

The option is valid only if the corresponding formatting argument is of standard signed or unsigned integer type.

If its value is negative, an exception of type format_error is thrown.

11

#

If positive-integer is used in awidth option, the value of the positive-integer is interpreted as a decimal integer and used as the value of the option.

12

#

For the purposes of width computation, a string is assumed to be in a locale-independent,implementation-defined encoding.

Implementations should use either UTF-8, UTF-16, or UTF-32, on platforms capable of displaying Unicode text in a terminal.

[Note 6:

This is the case for Windows®-based237 and many POSIX-based operating systems.

— end note]

13

#

For a sequence of characters in UTF-8, UTF-16, or UTF-32, an implementation should use as its field width the sum of the field widths of the first code point of each extended grapheme cluster.

Extended grapheme clusters are defined by UAX #29 of the Unicode Standard.

The following code points have a field width of 2:

any code point with the East_Asian_Width="W" orEast_Asian_Width="F" property as described by UAX #44 of the Unicode Standard

U+4dc0 – U+4dff (Yijing Hexagram Symbols)

U+1f300 – U+1f5ff (Miscellaneous Symbols and Pictographs)

U+1f900 – U+1f9ff (Supplemental Symbols and Pictographs)

The field width of all other code points is 1.

14

#

For a sequence of characters in neither UTF-8, UTF-16, nor UTF-32, the field width is unspecified.

15

#

The precision option is valid for floating-point and string types.

For floating-point types, the value of this option specifies the precision to be used for the floating-point presentation type.

For string types, this option specifies the longest prefix of the formatted argument to be included in the replacement field such that the field width of the prefix is no greater than the value of this option.

16

#

If nonnegative-integer is used in a precision option, the value of the decimal integer is used as the value of the option.

17

#

When the L option is used, the form used for the conversion is called the locale-specific form.

The L option is only valid for arithmetic types, and its effect depends upon the type.

  • (17.1)

    For integral types, the locale-specific form causes the context's locale to be used to insert the appropriate digit group separator characters.

  • (17.2)

    For floating-point types, the locale-specific form causes the context's locale to be used to insert the appropriate digit group and radix separator characters.

  • (17.3)

    For the textual representation of bool, the locale-specific form causes the context's locale to be used to insert the appropriate string as if obtained with numpunct::truename or numpunct::falsename.

18

#

The type determines how the data should be presented.

19

#

The available string presentation types are specified in Table 106.

Table 106 — Meaning of type options for strings [tab:format.type.string]

🔗
Type
Meaning
🔗
none, s
Copies the string to the output.
🔗
?
Copies the escaped string ([format.string.escaped]) to the output.

20

#

The meaning of some non-string presentation types is defined in terms of a call to to_chars.

In such cases, let [first, last) be a range large enough to hold the to_chars output and value be the formatting argument value.

Formatting is done as if by calling to_chars as specified and copying the output through the output iterator of the format context.

[Note 7:

Additional padding and adjustments are performed prior to copying the output through the output iterator as specified by the format specifiers.

— end note]

21

#

The available integer presentation types for integral types other than bool and charT are specified in Table 107.

[Example 4: string s0 = format("{}", 42); // value of s0 is "42" string s1 = format("{0:b} {0:d} {0:o} {0:x}", 42); // value of s1 is "101010 42 52 2a" string s2 = format("{0:#x} {0:#X}", 42); // value of s2 is "0x2a 0X2A" string s3 = format("{:L}", 1234); // value of s3 can be "1,234"// (depending on the locale) — end example]

Table 107 — Meaning of type options for integer types [tab:format.type.int]

🔗
Type
Meaning
🔗
b
to_chars(first, last, value, 2); the base prefix is 0b.
🔗
B
The same as b, except that the base prefix is 0B.
🔗
c
Copies the character static_cast(value) to the output.
Throws format_error if value is not in the range of representable values for charT.
🔗
d
to_chars(first, last, value).
🔗
o
to_chars(first, last, value, 8); the base prefix is 0 if value is nonzero and is empty otherwise.
🔗
x
to_chars(first, last, value, 16); the base prefix is 0x.
🔗
X
The same as x, except that it uses uppercase letters for digits above 9 and the base prefix is 0X.
🔗
none
The same as d.
[Note 8:
If the formatting argument type is charT or bool, the default is instead c or s, respectively. — end note]

22

#

The available charT presentation types are specified in Table 108.

Table 108 — Meaning of type options for charT [tab:format.type.char]

🔗
Type
Meaning
🔗
none, c
Copies the character to the output.
🔗
b, B, d, o, x, X
As specified in Table 107 with value converted to the unsigned version of the underlying type.
🔗
?
Copies the escaped character ([format.string.escaped]) to the output.

23

#

The available bool presentation types are specified in Table 109.

Table 109 — Meaning of type options for bool [tab:format.type.bool]

🔗
Type
Meaning
🔗
none, s
Copies textual representation, either true or false, to the output.
🔗
b, B, d, o, x, X
As specified in Table 107 for the value static_cast(value).

24

#

The available floating-point presentation types and their meanings for values other than infinity and NaN are specified in Table 110.

For lower-case presentation types, infinity and NaN are formatted asinf and nan, respectively.

For upper-case presentation types, infinity and NaN are formatted asINF and NAN, respectively.

[Note 9:

In either case, a sign is included if indicated by the sign option.

— end note]

Table 110 — Meaning of type options for floating-point types [tab:format.type.float]

🔗
Type
Meaning
🔗
a
If precision is specified, equivalent to to_chars(first, last, value, chars_format::hex, precision) where precision is the specified formatting precision; equivalent to to_chars(first, last, value, chars_format::hex) otherwise.
🔗
A
The same as a, except that it uses uppercase letters for digits above 9 and P to indicate the exponent.
🔗
e
Equivalent to to_chars(first, last, value, chars_format::scientific, precision) where precision is the specified formatting precision, or 6 if precision is not specified.
🔗
E
The same as e, except that it uses E to indicate exponent.
🔗
f, F
Equivalent to to_chars(first, last, value, chars_format::fixed, precision) where precision is the specified formatting precision, or 6 if precision is not specified.
🔗
g
Equivalent to to_chars(first, last, value, chars_format::general, precision) where precision is the specified formatting precision, or 6 if precision is not specified.
🔗
G
The same as g, except that it uses E to indicate exponent.
🔗
none
If precision is specified, equivalent to to_chars(first, last, value, chars_format::general, precision) where precision is the specified formatting precision; equivalent to to_chars(first, last, value) otherwise.

25

#

The available pointer presentation types and their mapping toto_chars are specified in Table 111.

[Note 10:

Pointer presentation types also apply to nullptr_t.

— end note]

Table 111 — Meaning of type options for pointer types [tab:format.type.ptr]

🔗
Type
Meaning
🔗
none, p
If uintptr_t is defined, to_chars(first, last, reinterpret_cast<uintptr_t>(value), 16) with the prefix 0x inserted immediately before the output of to_chars; otherwise, implementation-defined.
🔗
P
The same as p, except that it uses uppercase letters for digits above 9 and the base prefix is 0X.

237)237)

Windows® is a registered trademark of Microsoft Corporation.

This information is given for the convenience of users of this document and does not constitute an endorsement by ISO or IEC of this product.

28.5.3 Error reporting [format.err.report]

1

#

Formatting functions throw format_error if an argument fmt is passed that is not a format string for args.

They propagate exceptions thrown by operations offormatter specializations and iterators.

Failure to allocate storage is reported by throwing an exception as described in [res.on.exception.handling].

28.5.4 Class template basic_format_string [format.fmt.string]

namespace std {template<class charT, class... Args>struct basic_format_string {private: basic_string_view str; // exposition onlypublic:template consteval basic_format_string(const T& s); basic_format_string(runtime-format-string s) noexcept : str(s.str) {}constexpr basic_string_view get() const noexcept { return str; }};}

🔗

template<class T> consteval basic_format_string(const T& s);

1

#

Constraints: const T& models convertible_to<basic_string_view>.

2

#

Effects: Direct-non-list-initializes str with s.

3

#

Remarks: A call to this function is not a core constant expression ([expr.const]) unless there exist args of types Args such that str is a format string for args.

28.5.5 Formatting functions [format.functions]

1

#

In the description of the functions, operator + is used for some of the iterator categories for which it does not have to be defined.

In these cases the semantics of a + n are the same as in [algorithms.requirements].

🔗

template<class... Args> string format(format_string<Args...> fmt, Args&&... args);

2

#

Effects: Equivalent to:return vformat(fmt.str, make_format_args(args...));

🔗

template<class... Args> wstring format(wformat_string<Args...> fmt, Args&&... args);

3

#

Effects: Equivalent to:return vformat(fmt.str, make_wformat_args(args...));

🔗

template<class... Args> string format(const locale& loc, format_string<Args...> fmt, Args&&... args);

4

#

Effects: Equivalent to:return vformat(loc, fmt.str, make_format_args(args...));

🔗

template<class... Args> wstring format(const locale& loc, wformat_string<Args...> fmt, Args&&... args);

5

#

Effects: Equivalent to:return vformat(loc, fmt.str, make_wformat_args(args...));

🔗

string vformat(string_view fmt, format_args args); wstring vformat(wstring_view fmt, wformat_args args); string vformat(const locale& loc, string_view fmt, format_args args); wstring vformat(const locale& loc, wstring_view fmt, wformat_args args);

6

#

Returns: A string object holding the character representation of formatting arguments provided by args formatted according to specifications given in fmt.

If present, loc is used for locale-specific formatting.

7

#

Throws: As specified in [format.err.report].

🔗

template<class Out, class... Args> Out format_to(Out out, format_string<Args...> fmt, Args&&... args);

8

#

Effects: Equivalent to:return vformat_to(std::move(out), fmt.str, make_format_args(args...));

🔗

template<class Out, class... Args> Out format_to(Out out, wformat_string<Args...> fmt, Args&&... args);

9

#

Effects: Equivalent to:return vformat_to(std::move(out), fmt.str, make_wformat_args(args...));

🔗

template<class Out, class... Args> Out format_to(Out out, const locale& loc, format_string<Args...> fmt, Args&&... args);

10

#

Effects: Equivalent to:return vformat_to(std::move(out), loc, fmt.str, make_format_args(args...));

🔗

template<class Out, class... Args> Out format_to(Out out, const locale& loc, wformat_string<Args...> fmt, Args&&... args);

11

#

Effects: Equivalent to:return vformat_to(std::move(out), loc, fmt.str, make_wformat_args(args...));

🔗

template<class Out> Out vformat_to(Out out, string_view fmt, format_args args); template<class Out> Out vformat_to(Out out, wstring_view fmt, wformat_args args); template<class Out> Out vformat_to(Out out, const locale& loc, string_view fmt, format_args args); template<class Out> Out vformat_to(Out out, const locale& loc, wstring_view fmt, wformat_args args);

12

#

Let charT be decltype(fmt)::value_type.

13

#

Constraints: Out satisfies output_iterator<const charT&>.

14

#

Preconditions: Out models output_iterator<const charT&>.

15

#

Effects: Places the character representation of formatting the arguments provided by args, formatted according to the specifications given in fmt, into the range [out, out + N), where N is the number of characters in that character representation.

If present, loc is used for locale-specific formatting.

16

#

Returns: out + N.

17

#

Throws: As specified in [format.err.report].

🔗

template<class Out, class... Args> format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n, wformat_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n, const locale& loc, format_string<Args...> fmt, Args&&... args); template<class Out, class... Args> format_to_n_result<Out> format_to_n(Out out, iter_difference_t<Out> n, const locale& loc, wformat_string<Args...> fmt, Args&&... args);

18

#

Let

charT be decltype(fmt.str)::value_type,

N beformatted_size(fmt, args...) for the functions without a loc parameter andformatted_size(loc, fmt, args...) for the functions with a loc parameter, and

M be clamp(n, 0, N).

19

#

Constraints: Out satisfies output_iterator<const charT&>.

20

#

Preconditions: Out models output_iterator<const charT&>, andformatter<remove_cvref_t, charT> meets the BasicFormatter requirements ([formatter.requirements]) for each Ti in Args.

21

#

Effects: Places the first M characters of the character representation of formatting the arguments provided by args, formatted according to the specifications given in fmt, into the range [out, out + M).

If present, loc is used for locale-specific formatting.

22

#

Returns: {out + M, N}.

23

#

Throws: As specified in [format.err.report].

🔗

template<class... Args> size_t formatted_size(format_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(wformat_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(const locale& loc, format_string<Args...> fmt, Args&&... args); template<class... Args> size_t formatted_size(const locale& loc, wformat_string<Args...> fmt, Args&&... args);

24

#

Let charT be decltype(fmt.str)::value_type.

25

#

Preconditions: formatter<remove_cvref_t, charT> meets the BasicFormatter requirements ([formatter.requirements]) for each Ti in Args.

26

#

Returns: The number of characters in the character representation of formatting arguments args formatted according to specifications given in fmt.

If present, loc is used for locale-specific formatting.

27

#

Throws: As specified in [format.err.report].

28.5.6 Formatter [format.formatter]

28.5.6.1 Formatter requirements [formatter.requirements]

1

#

A type F meets the BasicFormatter requirements if it meets the

Cpp17DefaultConstructible (Table 30),

Cpp17CopyConstructible (Table 32),

Cpp17CopyAssignable (Table 34),

Cpp17Swappable ([swappable.requirements]), and

Cpp17Destructible (Table 35)

requirements, and the expressions shown in Table 112 are valid and have the indicated semantics.

2

#

A type F meets the Formatter requirements if it meets the BasicFormatter requirements and the expressions shown in Table 113 are valid and have the indicated semantics.

3

#

Given character type charT, output iterator typeOut, and formatting argument type T, in Table 112 and Table 113:

f is a value of type (possibly const) F,

g is an lvalue of type F,

u is an lvalue of type T,

t is a value of a type convertible to (possibly const) T,

PC is basic_format_parse_context,

FC is basic_format_context<Out, charT>,

pc is an lvalue of type PC, and

fc is an lvalue of type FC.

pc.begin() points to the beginning of theformat-spec ([format.string]) of the replacement field being formatted in the format string.

If format-spec is not present or empty then eitherpc.begin() == pc.end() or*pc.begin() == '}'.

Table 112BasicFormatter requirements [tab:formatter.basic]

🔗
Expression
Return type Requirement
🔗
g.parse(pc)
PC::iterator Parses format-spec ([format.string]) for type T in the range [pc.begin(), pc.end()) until the first unmatched character.
Throws format_error unless the whole range is parsed or the unmatched character is }.
[Note 1:
This allows formatters to emit meaningful error messages. — end note]
Stores the parsed format specifiers in *this and returns an iterator past the end of the parsed range.
🔗
f.format(u, fc)
FC::iterator Formats u according to the specifiers stored in *this, writes the output to fc.out(), and returns an iterator past the end of the output range.
The output shall only depend on u, fc.locale(), fc.arg(n) for any value n of type size_t, and the range [pc.begin(), pc.end()) from the last call to f.parse(pc).

Table 113Formatter requirements [tab:formatter]

🔗
Expression
Return type Requirement
🔗
f.format(t, fc)
FC::iterator Formats t according to the specifiers stored in *this, writes the output to fc.out(), and returns an iterator past the end of the output range.
The output shall only depend on t, fc.locale(), fc.arg(n) for any value n of type size_t, and the range [pc.begin(), pc.end()) from the last call to f.parse(pc).
🔗
f.format(u, fc)
FC::iterator As above, but does not modify u.

28.5.6.2 Formatter locking [format.formatter.locking]

🔗

template<class T> constexpr bool enable_nonlocking_formatter_optimization = false;

1

#

Remarks: Pursuant to [namespace.std], users may specialize enable_nonlocking_formatter_optimization for cv-unqualified program-defined types.

Such specializations shall be usable in constant expressions ([expr.const]) and have type const bool.

28.5.6.3 Concept formattable [format.formattable]

1

#

Let fmt-iter-for be an unspecified type that modelsoutput_iterator<const charT&> ([iterator.concept.output]).

template<class T, class Context, class Formatter = typename Context::template formatter_type<remove_const_t>>concept formattable-with = // exposition onlysemiregular &&requires(Formatter& f, const Formatter& cf, T&& t, Context fc, basic_format_parse_context pc){{ f.parse(pc) } -> same_as<typename decltype(pc)::iterator>; { cf.format(t, fc) } -> same_as; };

template<class T, class charT>concept formattable =formattable-with<remove_reference_t, basic_format_context<fmt-iter-for, charT>>;

2

#

A type T and a character type charT model formattable if formatter<remove_cvref_t, charT> meets the BasicFormatter requirements ([formatter.requirements]) and, if remove_reference_t is const-qualified, the Formatter requirements.

28.5.6.4 Formatter specializations [format.formatter.spec]

1

#

The functions defined in [format.functions] use specializations of the class template formatter to format individual arguments.

2

#

Let charT be either char or wchar_t.

Each specialization of formatter is either enabled or disabled, as described below.

A debug-enabled specialization of formatter additionally provides a public, constexpr, non-static member function set_debug_format() which modifies the state of the formatter to be as if the type of the std-format-spec parsed by the last call to parse were ?.

Each header that declares the template formatter provides the following enabled specializations:

The debug-enabled specializationstemplate<> struct formatter<char, char>;template<> struct formatter<char, wchar_t>;template<> struct formatter<wchar_t, wchar_t>;

For each charT, the debug-enabled string type specializationstemplate<> struct formatter<charT*, charT>;template<> struct formatter<const charT*, charT>;template<size_t N> struct formatter<charT[N], charT>;template<class traits, class Allocator>struct formatter<basic_string<charT, traits, Allocator>, charT>;templatestruct formatter<basic_string_view<charT, traits>, charT>;

For each charT, for each cv-unqualified arithmetic type ArithmeticT other thanchar,wchar_t,char8_t,char16_t, orchar32_t, a specializationtemplate<> struct formatter<ArithmeticT, charT>;

For each charT, the pointer type specializationstemplate<> struct formatter<nullptr_t, charT>;template<> struct formatter<void*, charT>;template<> struct formatter<const void*, charT>;

The parse member functions of these formatters interpret the format specification as a std-format-spec as described in [format.string.std].

3

#

Unless specified otherwise, for each type T for which a formatter specialization is provided by the library, each of the headers provides the following specialization:template<> inline constexpr bool enable_nonlocking_formatter_optimization = true;

[Note 1:

Specializations such as formatter<wchar_t, char> that would require implicit multibyte / wide string or character conversion are disabled.

— end note]

4

#

The header provides the following disabled specializations:

The string type specializationstemplate<> struct formatter<char*, wchar_t>;template<> struct formatter<const char*, wchar_t>;template<size_t N> struct formatter<char[N], wchar_t>;template<class traits, class Allocator>struct formatter<basic_string<char, traits, Allocator>, wchar_t>;templatestruct formatter<basic_string_view<char, traits>, wchar_t>;

5

#

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

6

#

If the library provides an explicit or partial specialization offormatter<T, charT>, that specialization is enabled and meets the Formatter requirements except as noted otherwise.

7

#

If F is a disabled specialization of formatter, these values are false:

is_default_constructible_v,

is_copy_constructible_v,

is_move_constructible_v,

is_copy_assignable_v, and

is_move_assignable_v.

8

#

An enabled specialization formatter<T, charT> meets theBasicFormatter requirements ([formatter.requirements]).

[Example 1: #include #include enum color { red, green, blue };const char* color_names[] = { "red", "green", "blue" };

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

struct err {};

std::string s0 = std::format("{}", 42); // OK, library-provided formatter std::string s1 = std::format("{}", L"foo"); // error: disabled formatter std::string s2 = std::format("{}", red); // OK, user-provided formatter std::string s3 = std::format("{}", err{}); // error: disabled formatter — end example]

28.5.6.5 Formatting escaped characters and strings [format.string.escaped]

1

#

A character or string can be formatted as escaped to make it more suitable for debugging or for logging.

2

#

The escaped string E representation of a string S is constructed by encoding a sequence of characters as follows.

The associated character encoding CE for charT (Table 12) is used to both interpret S and construct E.

  • (2.1)

    U+0022 quotation mark (") is appended to E.

  • (2.2)

    For each code unit sequence X in S that either encodes a single character, is a shift sequence, or is a sequence of ill-formed code units, processing is in order as follows:

    • (2.2.1)

      If X encodes a single character C, then:

      • [(2.2.1.1)](#string.escaped-2.2.1.1)
        If *C* is one of the characters in Table [114](#tab:format.escape.sequences "Table 114: Mapping of characters to escape sequences"),
        

then the two characters shown as the corresponding escape sequence are appended to E.

+
      [(2.2.1.2)](#string.escaped-2.2.1.2)
      Otherwise, if *C* is not U+0020 space and

  - [(2.2.1.2.1)](#string.escaped-2.2.1.2.1)

CE is UTF-8, UTF-16, or UTF-32 andC corresponds to a Unicode scalar value whose Unicode property General_Category has a value in the groupsSeparator (Z) or Other (C), as described by UAX #44 of the Unicode Standard, or

  - [(2.2.1.2.2)](#string.escaped-2.2.1.2.2)

CE is UTF-8, UTF-16, or UTF-32 andC corresponds to a Unicode scalar value with the Unicode property Grapheme_Extend=Yes as described by UAX #44 of the Unicode Standard andC is not immediately preceded in S by a character P appended to E without translation to an escape sequence, or

  - [(2.2.1.2.3)](#string.escaped-2.2.1.2.3)

CE is neither UTF-8, UTF-16, nor UTF-32 andC is one of an implementation-defined set of separator or non-printable characters

      then the sequence \u{*hex-digit-sequence*} is appended to *E*,

where hex-digit-sequence is the shortest hexadecimal representation of C using lower-case hexadecimal digits.

+
      [(2.2.1.3)](#string.escaped-2.2.1.3)
      Otherwise, *C* is appended to *E*[.](#string.escaped-2.2.1.3.sentence-1)
  • (2.2.2)

    Otherwise, if X is a shift sequence, the effect on E and further decoding of S is unspecified. Recommended practice: A shift sequence should be represented in E such that the original code unit sequence of S can be reconstructed.

  • (2.2.3)

    Otherwise (X is a sequence of ill-formed code units), each code unit U is appended to E in order as the sequence \x{hex-digit-sequence}, where hex-digit-sequence is the shortest hexadecimal representation of U using lower-case hexadecimal digits.

  • (2.3)

    Finally, U+0022 quotation mark (") is appended to E.

Table 114 — Mapping of characters to escape sequences [tab:format.escape.sequences]

🔗
Character
Escape sequence
🔗
U+0009 character tabulation
\t
🔗
U+000a line feed
\n
🔗
U+000d carriage return
\r
🔗
U+0022 quotation mark
"
🔗
U+005c reverse solidus
\

3

#

The escaped string representation of a character C is equivalent to the escaped string representation of a string of C, except that:

the result starts and ends with U+0027 apostrophe (') instead of U+0022 quotation mark ("), and

if C is U+0027 apostrophe, the two characters ' are appended to E, and

if C is U+0022 quotation mark, then C is appended unchanged.

[Example 1: string s0 = format("[{}]", "h\tllo"); // s0 has value: [h llo] string s1 = format("[{:?}]", "h\tllo"); // s1 has value: ["h\tllo"] string s2 = format("[{:?}]", "Спасибо, Виктор ♥!"); // s2 has value: ["Спасибо, Виктор ♥!"] string s3 = format("[{:?}, {:?}]", ''', '"'); // s3 has value: [''', '"']// The following examples assume use of the UTF-8 encoding string s4 = format("[{:?}]", string("\0 \n \t \x02 \x1b", 9)); // s4 has value: ["\u{0} \n \t \u{2} \u{1b}"] string s5 = format("[{:?}]", "\xc3\x28"); // invalid UTF-8, s5 has value: ["\x{c3}("] string s6 = format("[{:?}]", "🤷🏻‍♂️"); // s6 has value: ["🤷\u{200d}♂"] string s7 = format("[{:?}]", "\u0301"); // s7 has value: ["\u{301}"] string s8 = format("[{:?}]", "\\u0301"); // s8 has value: ["\\u{301}"] string s9 = format("[{:?}]", "e\u0301\u0323"); // s9 has value: ["ẹ́"] — end example]

28.5.6.6 Class template basic_format_parse_context [format.parse.ctx]

🔗

namespace std {templateclass basic_format_parse_context {public:using char_type = charT; using const_iterator = typename basic_string_view::const_iterator; using iterator = const_iterator; private: iterator begin_; // exposition only iterator end_; // exposition onlyenum indexing { unknown, manual, automatic }; // exposition only indexing indexing_; // exposition only size_t next_arg_id_; // exposition only size_t num_args_; // exposition onlypublic:constexpr explicit basic_format_parse_context(basic_string_view fmt) noexcept; basic_format_parse_context(const basic_format_parse_context&) = delete; basic_format_parse_context& operator=(const basic_format_parse_context&) = delete; 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); template<class... Ts>constexpr void check_dynamic_spec(size_t id) noexcept; constexpr void check_dynamic_spec_integral(size_t id) noexcept; constexpr void check_dynamic_spec_string(size_t id) noexcept; };}

1

#

An instance of basic_format_parse_context holds the format string parsing state, consisting of the format string range being parsed and the argument counter for automatic indexing.

2

#

If a program declares an explicit or partial specialization ofbasic_format_parse_context, the program is ill-formed, no diagnostic required.

🔗

constexpr explicit basic_format_parse_context(basic_string_view<charT> fmt) noexcept;

3

#

Effects: Initializesbegin_ with fmt.begin(),end_ with fmt.end(),indexing_ with unknown,next_arg_id_ with 0, andnum_args_ with 0.

[Note 1:

Any call tonext_arg_id, check_arg_id, or check_dynamic_spec on an instance of basic_format_parse_context initialized using this constructor is not a core constant expression.

— end note]

🔗

constexpr const_iterator begin() const noexcept;

4

#

Returns: begin_.

🔗

constexpr const_iterator end() const noexcept;

5

#

Returns: end_.

🔗

constexpr void advance_to(const_iterator it);

6

#

Preconditions: end() is reachable from it.

7

#

Effects: Equivalent to: begin_ = it;

🔗

constexpr size_t next_arg_id();

8

#

Effects: If indexing_ != manual is true, equivalent to:if (indexing_ == unknown) indexing_ = automatic;return next_arg_id_++;

9

#

Throws: format_error if indexing_ == manual is true.

[Note 2:

This indicates mixing of automatic and manual argument indexing.

— end note]

10

#

Remarks: Let cur-arg-id be the value of next_arg_id_ prior to this call.

Call expressions where cur-arg-id >= num_args_ is true are not core constant expressions ([expr.const]).

🔗

constexpr void check_arg_id(size_t id);

11

#

Effects: If indexing_ != automatic is true, equivalent to:if (indexing_ == unknown) indexing_ = manual;

12

#

Throws: format_error ifindexing_ == automatic is true.

[Note 3:

This indicates mixing of automatic and manual argument indexing.

— end note]

13

#

Remarks: A call to this function is a core constant expression ([expr.const]) only ifid < num_args_ is true.

🔗

template<class... Ts> constexpr void check_dynamic_spec(size_t id) noexcept;

14

#

Mandates: sizeof...(Ts) ≥ 1.

The types in Ts... are unique.

Each type in Ts... is one ofbool,char_type,int,unsigned int,long long int,unsigned long long int,float,double,long double,const char_type*,basic_string_view<char_type>, orconst void*.

15

#

Remarks: A call to this function is a core constant expression only if

id < num_args_ is true and

the type of the corresponding format argument (after conversion to basic_format_arg) is one of the types in Ts....

🔗

constexpr void check_dynamic_spec_integral(size_t id) noexcept;

16

#

Effects: Equivalent to:check_dynamic_spec<int, unsigned int, long long int, unsigned long long int>(id);

🔗

constexpr void check_dynamic_spec_string(size_t id) noexcept;

17

#

Effects: Equivalent to:check_dynamic_spec<const char_type*, basic_string_view<char_type>>(id);

28.5.6.7 Class template basic_format_context [format.context]

🔗

namespace std {template<class Out, class charT>class basic_format_context { basic_format_args<basic_format_context> args_; // exposition only Out out_; // exposition only basic_format_context(const basic_format_context&) = delete; basic_format_context& operator=(const basic_format_context&) = delete; public:using iterator = Out; using char_type = charT; template using formatter_type = formatter<T, charT>;

basic_format_arg<basic_format_context> arg(size_t id) const noexcept; std::locale locale();

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

1

#

An instance of basic_format_context holds formatting state consisting of the formatting arguments and the output iterator.

2

#

If a program declares an explicit or partial specialization ofbasic_format_context, the program is ill-formed, no diagnostic required.

3

#

Out shall model output_iterator<const charT&>.

4

#

format_context is an alias for a specialization of basic_format_context with an output iterator that appends to string, such as back_insert_iterator.

Similarly, wformat_context is an alias for a specialization of basic_format_context with an output iterator that appends to wstring.

5

#

Recommended practice: For a given type charT, implementations should provide a single instantiation of basic_format_context for appending tobasic_string,vector, or any other container with contiguous storage by wrapping those in temporary objects with a uniform interface (such as a span) and polymorphic reallocation.

🔗

basic_format_arg<basic_format_context> arg(size_t id) const noexcept;

6

#

Returns: args_.get(id).

🔗

std::locale locale();

7

#

Returns: The locale passed to the formatting function if the latter takes one, and std::locale() otherwise.

🔗

iterator out();

8

#

Effects: Equivalent to: return std::move(out_);

🔗

void advance_to(iterator it);

9

#

Effects: Equivalent to: out_ = std::move(it);

[Example 1: struct S { int value; };

template<> struct std::formatter { size_t width_arg_id = 0; // Parses a width argument id in the format { digit }.constexpr auto parse(format_parse_context& ctx) {auto iter = ctx.begin(); auto is_digit = [](auto c) { return c >= '0' && c <= '9'; }; auto get_char = & { return iter != ctx.end() ? *iter : 0; }; if (get_char() != '{')return iter; ++iter; char c = get_char(); if (!is_digit(c) || (++iter, get_char()) != '}')throw format_error("invalid format"); width_arg_id = c - '0'; ctx.check_arg_id(width_arg_id); return ++iter; }// Formats an S with width given by the argument width_arg_id.auto format(S s, format_context& ctx) const {int width = ctx.arg(width_arg_id).visit([](auto value) -> int {if constexpr (!is_integral_v<decltype(value)>)throw format_error("width is not integral"); else if (value < 0 || value > numeric_limits::max())throw format_error("invalid width"); elsereturn value; }); return format_to(ctx.out(), "{0:x>{1}}", s.value, width); }};

std::string s = std::format("{0:{1}}", S{42}, 10); // value of s is "xxxxxxxx42" — end example]

28.5.7 Formatting of ranges [format.range]

28.5.7.1 Variable template format_kind [format.range.fmtkind]

🔗

template<ranges::[input_range](range.refinements#concept:input_range "25.4.6Other range refinements[range.refinements]") R> requires [same_as](concept.same#concept:same_as "18.4.2Concept same_­as[concept.same]")<R, remove_cvref_t<R>> constexpr range_format format_kind<R> = see below;

1

#

A program that instantiates the primary template of format_kind is ill-formed.

2

#

For a type R, format_kind is defined as follows:

  • (2.1)

    If same_as<remove_cvref_t<ranges::range_reference_t>, R> is true,format_kind is range_format::disabled. [Note 1: This prevents constraint recursion for ranges whose reference type is the same range type. For example,std::filesystem::path is a range of std::filesystem::path. — end note]

  • (2.2)

    Otherwise, if the qualified-id R::key_type is valid and denotes a type:

    • (2.2.1)

      If the qualified-id R::mapped_type is valid and denotes a type, let U be remove_cvref_t<ranges::range_reference_t>. If either U is a specialization of pair orU is a specialization of tuple andtuple_size_v == 2,format_kind is range_format::map.

    • (2.2.2)

      Otherwise, format_kind is range_format::set.

  • (2.3)

    Otherwise, format_kind is range_format::sequence.

3

#

Remarks: Pursuant to [namespace.std], users may specialize format_kind for cv-unqualified program-defined types that model ranges::input_range.

Such specializations shall be usable in constant expressions ([expr.const]) and have type const range_format.

28.5.7.2 Class template range_formatter [format.range.formatter]

🔗

namespace std {template<class T, class charT = char>requires same_as<remove_cvref_t, T> && formattable<T, charT>class range_formatter { formatter<T, charT> underlying_; // exposition only basic_string_view separator_ = STATICALLY-WIDEN(", "); // exposition only basic_string_view opening-bracket_ = STATICALLY-WIDEN("["); // exposition only basic_string_view closing-bracket_ = STATICALLY-WIDEN("]"); // exposition onlypublic:constexpr void set_separator(basic_string_view sep) noexcept; constexpr void set_brackets(basic_string_view opening, basic_string_view closing) noexcept; constexpr formatter<T, charT>& underlying() noexcept { return underlying_; }constexpr const formatter<T, charT>& underlying() const noexcept { return underlying_; }templateconstexpr typename ParseContext::iterator parse(ParseContext& ctx); template<ranges::input_range R, class FormatContext>requires formattable<ranges::range_reference_t, charT> &&same_as<remove_cvref_t<ranges::range_reference_t>, T>typename FormatContext::iterator format(R&& r, FormatContext& ctx) const; };}

1

#

The class template range_formatter is a utility for implementing formatter specializations for range types.

2

#

range_formatter interprets format-spec as a range-format-spec.

The syntax of format specifications is as follows:

range-format-spec :
range-fill-and-alignopt widthopt nopt range-typeopt range-underlying-specopt

range-fill-and-align :
range-fillopt align

range-fill :
any character other than { or } or :

range-type :
m
s
?s

range-underlying-spec :
format-spec

3

#

For range_formatter<T, charT>, the format-spec in a range-underlying-spec, if any, is interpreted by formatter<T, charT>.

4

#

The range-fill-and-align is interpreted the same way as a fill-and-align ([format.string.std]).

The productions align and width are described in [format.string].

5

#

The n option causes the range to be formatted without the opening and closing brackets.

[Note 1:

This is equivalent to invoking set_brackets({}, {}).

— end note]

6

#

The range-type specifier changes the way a range is formatted, with certain options only valid with certain argument types.

The meaning of the various type options is as specified in Table 115.

Table 115 — Meaning of range-type options [tab:formatter.range.type]

🔗
Option
Requirements Meaning
🔗
m
T shall be either a specialization of pair or a specialization of tuple such that tuple_size_v is 2. Indicates that the opening bracket should be "{", the closing bracket should be "}", the separator should be ", ", and each range element should be formatted as if m were specified for its tuple-type.
[Note 2:
If the n option is provided in addition to the m option, both the opening and closing brackets are still empty. — end note]
🔗
s
T shall be charT. Indicates that the range should be formatted as a string.
🔗
?s
T shall be charT. Indicates that the range should be formatted as an escaped string ([format.string.escaped]).

If the range-type is s or ?s, then there shall be no n option and no range-underlying-spec.

🔗

constexpr void set_separator(basic_string_view<charT> sep) noexcept;

7

#

Effects: Equivalent to: separator_ = sep;

🔗

constexpr void set_brackets(basic_string_view<charT> opening, basic_string_view<charT> closing) noexcept;

8

#

Effects: Equivalent to:opening-bracket_ = opening;closing-bracket_ = closing;

🔗

template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx);

9

#

Effects: Parses the format specifiers as a range-format-spec and stores the parsed specifiers in *this.

Calls underlying_.parse(ctx) to parseformat-spec in range-format-spec or, if the latter is not present, an empty format-spec.

The values ofopening-bracket_, closing-bracket_, and separator_ are modified if and only if required by the range-type or the n option, if present.

If:

the range-type is neither s nor ?s,

underlying_.set_debug_format() is a valid expression, and

there is no range-underlying-spec,

then calls underlying_.set_debug_format().

10

#

Returns: An iterator past the end of the range-format-spec.

🔗

template<ranges::[input_range](range.refinements#concept:input_range "25.4.6Other range refinements[range.refinements]") R, class FormatContext> requires [formattable](#concept:formattable "28.5.6.3Concept formattable[format.formattable]")<ranges::range_reference_t<R>, charT> && [same_as](concept.same#concept:same_as "18.4.2Concept same_­as[concept.same]")<remove_cvref_t<ranges::range_reference_t<R>>, T> typename FormatContext::iterator format(R&& r, FormatContext& ctx) const;

11

#

Effects: Writes the following into ctx.out(), adjusted according to the range-format-spec:

  • (11.1)

    If the range-type was s, then as if by formatting basic_string(from_range, r).

  • (11.2)

    Otherwise, if the range-type was ?s, then as if by formatting basic_string(from_range, r) as an escaped string ([format.string.escaped]).

  • (11.3)

    Otherwise,

opening-bracket_,

for each element e of the range r: + (11.3.2.1) the result of writing e via underlying_ and

+
      [(11.3.2.2)](#range.formatter-11.3.2.2)

separator_, unless e is the last element of r, and

closing-bracket_.

12

#

Returns: An iterator past the end of the output range.

28.5.7.3 Class template range-default-formatter [format.range.fmtdef]

🔗

namespace std {template<ranges::input_range R, class charT>struct range-default-formatter<range_format::sequence, R, charT> { // exposition onlyprivate:using maybe-const-r = fmt-maybe-const<R, charT>; // exposition only range_formatter<remove_cvref_t<ranges::range_reference_t<maybe-const-r>>, charT> underlying_; // exposition onlypublic:constexpr void set_separator(basic_string_view sep) noexcept; constexpr void set_brackets(basic_string_view opening, basic_string_view closing) noexcept; templateconstexpr typename ParseContext::iterator parse(ParseContext& ctx); templatetypename FormatContext::iterator format(maybe-const-r& elems, FormatContext& ctx) const; };}

🔗

constexpr void set_separator(basic_string_view<charT> sep) noexcept;

1

#

Effects: Equivalent to: underlying_.set_separator(sep);

🔗

constexpr void set_brackets(basic_string_view<charT> opening, basic_string_view<charT> closing) noexcept;

2

#

Effects: Equivalent to: underlying_.set_brackets(opening, closing);

🔗

template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx);

3

#

Effects: Equivalent to: return underlying_.parse(ctx);

🔗

template<class FormatContext> typename FormatContext::iterator format(maybe-const-r& elems, FormatContext& ctx) const;

4

#

Effects: Equivalent to: return underlying_.format(elems, ctx);

28.5.7.4 Specialization of range-default-formatter for maps [format.range.fmtmap]

🔗

namespace std {template<ranges::input_range R, class charT>struct range-default-formatter<range_format::map, R, charT> {private:using maybe-const-map = fmt-maybe-const<R, charT>; // exposition onlyusing element-type = // exposition only remove_cvref_t<ranges::range_reference_t<maybe-const-map>>; range_formatter<element-type, charT> underlying_; // exposition onlypublic:constexpr range-default-formatter(); templateconstexpr typename ParseContext::iterator parse(ParseContext& ctx); templatetypename FormatContext::iterator format(maybe-const-map& r, FormatContext& ctx) const; };}

🔗

constexpr range-default-formatter();

1

#

Mandates: Either:

element-type is a specialization of pair, or

element-type is a specialization of tuple andtuple_size_v<element-type> == 2.

2

#

Effects: Equivalent to:underlying_.set_brackets(STATICALLY-WIDEN("{"), STATICALLY-WIDEN("}"));underlying_.underlying().set_brackets({}, {});underlying_.underlying().set_separator(STATICALLY-WIDEN(": "));

🔗

template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx);

3

#

Effects: Equivalent to: return underlying_.parse(ctx);

🔗

template<class FormatContext> typename FormatContext::iterator format(maybe-const-map& r, FormatContext& ctx) const;

4

#

Effects: Equivalent to: return underlying_.format(r, ctx);

28.5.7.5 Specialization of range-default-formatter for sets [format.range.fmtset]

🔗

namespace std {template<ranges::input_range R, class charT>struct range-default-formatter<range_format::set, R, charT> {private:using maybe-const-set = fmt-maybe-const<R, charT>; // exposition only range_formatter<remove_cvref_t<ranges::range_reference_t<maybe-const-set>>, charT> underlying_; // exposition onlypublic:constexpr range-default-formatter(); templateconstexpr typename ParseContext::iterator parse(ParseContext& ctx); templatetypename FormatContext::iterator format(maybe-const-set& r, FormatContext& ctx) const; };}

🔗

constexpr range-default-formatter();

1

#

Effects: Equivalent to:underlying_.set_brackets(STATICALLY-WIDEN("{"), STATICALLY-WIDEN("}"));

🔗

template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx);

2

#

Effects: Equivalent to: return underlying_.parse(ctx);

🔗

template<class FormatContext> typename FormatContext::iterator format(maybe-const-set& r, FormatContext& ctx) const;

3

#

Effects: Equivalent to: return underlying_.format(r, ctx);

28.5.7.6 Specialization of range-default-formatter for strings [format.range.fmtstr]

🔗

namespace std {template<range_format K, ranges::input_range R, class charT>requires (K == range_format::string || K == range_format::debug_string)struct range-default-formatter<K, R, charT> {private: formatter<basic_string, charT> underlying_; // exposition onlypublic:templateconstexpr typename ParseContext::iterator parse(ParseContext& ctx); templatetypename FormatContext::iterator format(see below& str, FormatContext& ctx) const; };}

1

#

Mandates: same_as<remove_cvref_t<range_reference_t>, charT> is true.

🔗

template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx);

2

#

Effects: Equivalent to:auto i = underlying_.parse(ctx);if constexpr (K == range_format::debug_string) {underlying_.set_debug_format();}return i;

🔗

template<class FormatContext> typename FormatContext::iterator format(see below& r, FormatContext& ctx) const;

3

#

The type of r is const R& if ranges::input_range is true andR& otherwise.

4

#

Effects: Let s be a basic_string such thatranges::equal(s, r) is true.

Equivalent to: return underlying_.format(s, ctx);

28.5.8 Arguments [format.arguments]

28.5.8.1 Class template basic_format_arg [format.arg]

🔗

namespace std {templateclass basic_format_arg {public:class handle; private:using char_type = typename Context::char_type; // exposition only variant<monostate, bool, char_type, int, unsigned int, long long int, unsigned long long int, float, double, long double, const char_type*, basic_string_view<char_type>, const void*, handle> value; // exposition onlytemplate explicit basic_format_arg(T& v) noexcept; // exposition onlypublic: basic_format_arg() noexcept; explicit operator bool() const noexcept; templatedecltype(auto) visit(this basic_format_arg arg, Visitor&& vis); template<class R, class Visitor> R visit(this basic_format_arg arg, Visitor&& vis); };}

1

#

An instance of basic_format_arg provides access to a formatting argument for user-defined formatters.

2

#

The behavior of a program that adds specializations ofbasic_format_arg is undefined.

🔗

basic_format_arg() noexcept;

3

#

Postconditions: !(*this).

🔗

template<class T> explicit basic_format_arg(T& v) noexcept;

4

#

Constraints: T satisfies formattable-with.

5

#

Preconditions: If decay_t is char_type* or const char_type*,static_cast<const char_
type*>(v) points to an NTCTS ([defns.ntcts]).

6

#

Effects: Let TD be remove_const_t.

If TD is bool or char_type, initializes value with v;

otherwise, if TD is char and char_type iswchar_t, initializes value withstatic_cast<wchar_t>(static_cast(v));

otherwise, if TD is a signed integer type ([basic.fundamental]) and sizeof(TD) <= sizeof(int), initializes value with static_cast(v);

otherwise, if TD is an unsigned integer type andsizeof(TD) <= sizeof(unsigned int), initializesvalue with static_cast(v);

otherwise, if TD is a signed integer type andsizeof(TD) <= sizeof(long long int), initializesvalue with static_cast(v);

otherwise, if TD is an unsigned integer type andsizeof(TD) <= sizeof(unsigned long long int), initializesvalue withstatic_cast(v);

otherwise, if TD is a standard floating-point type, initializes value with v;

otherwise, if TD is a specialization of basic_string_view or basic_string andTD::value_type is char_type, initializes value withbasic_string_view<char_type>(v.data(), v.size());

otherwise, if decay_t ischar_type* or const char_type*, initializes value with static_cast<const char_type*>(v);

otherwise, if is_void_v<remove_pointer_t> is true oris_null_pointer_v is true, initializes value with static_cast<const void*>(v);

otherwise, initializes value with handle(v).

[Note 1:

Constructing basic_format_arg from a pointer to a member is ill-formed unless the user provides an enabled specialization of formatter for that pointer to member type.

— end note]

🔗

explicit operator bool() const noexcept;

7

#

Returns: !holds_alternative(value).

🔗

template<class Visitor> decltype(auto) visit(this basic_format_arg arg, Visitor&& vis);

8

#

Effects: Equivalent to: return arg.value.visit(std::forward(vis));

🔗

template<class R, class Visitor> R visit(this basic_format_arg arg, Visitor&& vis);

9

#

Effects: Equivalent to: return arg.value.visit(std::forward(vis));

10

#

The class handle allows formatting an object of a user-defined type.

🔗

namespace std {templateclass basic_format_arg::handle {const void* ptr_; // exposition onlyvoid (format_)(basic_format_parse_context<char_type>&, Context&, const void); // exposition onlytemplate explicit handle(T& val) noexcept; // exposition onlypublic:void format(basic_format_parse_context<char_type>&, Context& ctx) const; };}

🔗

template<class T> explicit handle(T& val) noexcept;

11

#

Let

TD be remove_const_t,

TQ be const TD ifconst TD satisfies formattable-with and TD otherwise.

12

#

Mandates: TQ satisfies formattable-with.

13

#

Effects: Initializesptr_ with addressof(val) andformat_ with[](basic_format_parse_context<char_type>& parse_ctx, Context& format_ctx, const void* ptr) {typename Context::template formatter_type f; parse_ctx.advance_to(f.parse(parse_ctx)); format_ctx.advance_to(f.format(const_cast<TQ>(static_cast<const TD*>(ptr)), format_ctx));}

🔗

void format(basic_format_parse_context<char_type>& parse_ctx, Context& format_ctx) const;

14

#

Effects: Equivalent to: format_(parse_ctx, format_ctx, ptr_);

28.5.8.2 Class template format-arg-store [format.arg.store]

namespace std {template<class Context, class... Args>class format-arg-store { // exposition only array<basic_format_arg, sizeof...(Args)> args; // exposition only};}

1

#

An instance of format-arg-store stores formatting arguments.

🔗

template<class Context = format_context, class... Args> format-arg-store<Context, Args...> make_format_args(Args&... fmt_args);

2

#

Preconditions: The typetypename Context::template formatter_type<remove_const_t>
meets the BasicFormatter requirements ([formatter.requirements]) for each Ti in Args.

3

#

Returns: An object of type format-arg-store<Context, Args...> whose args data member is initialized with{basic_format_arg(fmt_args)...}.

🔗

template<class... Args> format-arg-store<wformat_context, Args...> make_wformat_args(Args&... args);

4

#

Effects: Equivalent to:return make_format_args<wformat_context>(args...);

28.5.8.3 Class template basic_format_args [format.args]

namespace std {templateclass basic_format_args { size_t size_; // exposition onlyconst basic_format_arg* data_; // exposition onlypublic:template<class... Args> basic_format_args(const format-arg-store<Context, Args...>& store) noexcept;

basic_format_arg get(size_t i) const noexcept; }; template<class Context, class... Args> basic_format_args(format-arg-store<Context, Args...>) -> basic_format_args;}

1

#

An instance of basic_format_args provides access to formatting arguments.

Implementations should optimize the representation of basic_format_args for a small number of formatting arguments.

[Note 1:

For example, by storing indices of type alternatives separately from values and packing the former.

— end note]

🔗

template<class... Args> basic_format_args(const format-arg-store<Context, Args...>& store) noexcept;

2

#

Effects: Initializessize_ with sizeof...(Args) anddata_ with store.args.data().

🔗

basic_format_arg<Context> get(size_t i) const noexcept;

3

#

Returns: i < size_ ? data_[i] : basic_format_arg().

28.5.9 Tuple formatter [format.tuple]

1

#

For each of pair and tuple, the library provides the following formatter specialization where pair-or-tuple is the name of the template:

🔗

namespace std {template<class charT, formattable... Ts>struct formatter<pair-or-tuple<Ts...>, charT> {private: tuple<formatter<remove_cvref_t, charT>...> underlying_; // exposition only basic_string_view separator_ = STATICALLY-WIDEN(", "); // exposition only basic_string_view opening-bracket_ = STATICALLY-WIDEN("("); // exposition only basic_string_view closing-bracket_ = STATICALLY-WIDEN(")"); // exposition onlypublic:constexpr void set_separator(basic_string_view sep) noexcept; constexpr void set_brackets(basic_string_view opening, basic_string_view closing) noexcept; templateconstexpr typename ParseContext::iterator parse(ParseContext& ctx); templatetypename FormatContext::iterator format(see below& elems, FormatContext& ctx) const; }; template<class... Ts>constexpr bool enable_nonlocking_formatter_optimization<pair-or-tuple<Ts...>> =(enable_nonlocking_formatter_optimization && ...);}

2

#

The parse member functions of these formatters interpret the format specification as a tuple-format-spec according to the following syntax:

tuple-format-spec :
tuple-fill-and-alignopt widthopt tuple-typeopt

tuple-fill-and-align :
tuple-fillopt align

tuple-fill :
any character other than { or } or :

tuple-type :
m
n

3

#

The tuple-fill-and-align is interpreted the same way as a fill-and-align ([format.string.std]).

The productions align and width are described in [format.string].

4

#

The tuple-type specifier changes the way a pair or tuple is formatted, with certain options only valid with certain argument types.

The meaning of the various type options is as specified in Table 116.

Table 116 — Meaning of tuple-type options [tab:formatter.tuple.type]

🔗
Option
Requirements Meaning
🔗
m
sizeof...(Ts) == 2 Equivalent to: set_separator(STATICALLY-WIDEN(": ")); set_brackets({}, {});
🔗
n
none Equivalent to: set_brackets({}, {});
🔗
none
none No effects

🔗

constexpr void set_separator(basic_string_view<charT> sep) noexcept;

5

#

Effects: Equivalent to: separator_ = sep;

🔗

constexpr void set_brackets(basic_string_view<charT> opening, basic_string_view<charT> closing) noexcept;

6

#

Effects: Equivalent to:opening-bracket_ = opening;closing-bracket_ = closing;

🔗

template<class ParseContext> constexpr typename ParseContext::iterator parse(ParseContext& ctx);

7

#

Effects: Parses the format specifiers as a tuple-format-spec and stores the parsed specifiers in *this.

The values ofopening-bracket_,closing-bracket_, andseparator_ are modified if and only if required by the tuple-type, if present.

For each element e in underlying_, calls e.parse(ctx) to parse an empty format-spec and, if e.set_debug_format() is a valid expression, calls e.set_debug_format().

8

#

Returns: An iterator past the end of the tuple-format-spec.

🔗

template<class FormatContext> typename FormatContext::iterator format(see below& elems, FormatContext& ctx) const;

9

#

The type of elems is:

  • (9.1)

    If (formattable<const Ts, charT> && ...) is true,const pair-or-tuple<Ts...>&.

  • (9.2)

    Otherwise pair-or-tuple<Ts...>&.

10

#

Effects: Writes the following into ctx.out(), adjusted according to the tuple-format-spec:

opening-bracket_,

for each index I in the [0, sizeof...(Ts)):

if I != 0, separator_,

the result of writing get(elems) via get(underlying_), and

closing-bracket_.

11

#

Returns: An iterator past the end of the output range.

28.5.10 Class format_error [format.error]

🔗

namespace std {class format_error : public runtime_error {public:constexpr explicit format_error(const string& what_arg); constexpr explicit format_error(const char* what_arg); };}

1

#

The class format_error defines the type of objects thrown as exceptions to report errors from the formatting library.

🔗

constexpr format_error(const string& what_arg);

2

#

Postconditions: strcmp(what(), what_arg.c_str()) == 0.

🔗

constexpr format_error(const char* what_arg);

3

#

Postconditions: strcmp(what(), what_arg) == 0.