Namespaces
Variants
Views
Actions

std::runtime_format

From cppreference.com
< cpp‎ | utility‎ | format
Revision as of 00:31, 25 November 2023 by Cooky (Talk | contribs)

 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
 
 
Defined in header <format>
/*runtime-format-string*/<char> runtime_format( std::string_view fmt );
(1) (since C++26)
/*runtime-format-string*/<wchar_t> runtime_format( std::wstring_view fmt );
(2) (since C++26)

Returns an object that stores a runtime format string directly usable in user-oriented formatting functions and can be implicitly converted to std::basic_format_string.

1,2) Equivalent to return {fmt};.

Contents

Parameters

fmt - an object that represents the format string. The format string consists of
  • ordinary characters (except { and }), which are copied unchanged to the output,
  • escape sequences {{ and }}, which are replaced with { and } respectively in the output, and
  • replacement fields.

Each replacement field has the following format:

{ arg-id (optional) } (1)
{ arg-id (optional) : format-spec } (2)
1) replacement field without a format specification
2) replacement field with a format specification
arg-id - specifies the index of the argument in args whose value is to be used for formatting; if it is omitted, the arguments are used in order.

The arg-id s in a format string must all be present or all be omitted. Mixing manual and automatic indexing is an error.

format-spec - the format specification defined by the std::formatter specialization for the corresponding argument. Cannot start with }.

(since C++23)
(since C++26)
  • For other formattable types, the format specification is determined by user-defined formatter specializations.

Return value

An object holding the runtime format string.

Example

#include <format>
#include <print>
#include <string>
#include <string_view>
 
int main()
{
    std::print("Hello {}!\n", "world");
 
    std::string fmt;
    for (int i{}; i != 3; ++i)
    {
        fmt += "{} "; // constructs the formatting string
        std::print("{} : ", fmt);
        std::println(std::runtime_format(fmt), "alpha", 'Z', 3.14, "unused");
    }
}

Output:

Hello world!
{}  : alpha
{} {}  : alpha Z
{} {} {}  : alpha Z 3.14

See also

(C++20)
stores formatted representation of the arguments in a new string
(function template) [edit]
(C++20)
non-template variant of std::format using type-erased argument representation
(function) [edit]
class template that performs compile-time format string checks at construction time
(class template) [edit]