std::dynamic_format - cppreference.com
Namespaces
Variants

std::dynamic_format

From cppreference.com
 
 
 
 
Defined in header <format>
/*dynamic-format-string*/<char> dynamic_format( std::string_view fmt ) noexcept;
(1) (since C++26)
/*dynamic-format-string*/<wchar_t> dynamic_format( std::wstring_view fmt ) noexcept;
(2) (since C++26)

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

Parameters

fmt - a string view

Return value

An object of exposition-only type holding the dynamic format string:

Class template dynamic-format-string <CharT>

template< class CharT >
struct /*dynamic-format-string*/;
(since C++26)
(exposition only*)

Data members

Member Description
std::basic_string_view<CharT> str holds the format string
(exposition-only member object*)

Constructors and assignments

/*dynamic-format-string*/( std::basic_string_view<CharT> s ) noexcept;
(1) (since C++26)
/*dynamic-format-string*/( const /*dynamic-format-string*/& ) = delete;
(2) (since C++26)
/*dynamic-format-string*/& operator=( const /*dynamic-format-string*/& ) = delete;
(3) (since C++26)

The type is neither copyable nor movable.

1) Initializes str with s.
2) Copy constructor is explicitly deleted.
3) The assignment is explicitly deleted.

Notes

Since the return type of std::dynamic_format is neither copyable nor movable, an attempt of passing an object dynamic_fmt (see below) as glvalue inhibits the construction of std::basic_format_string which results in program ill-formed. To construct std::basic_format_string with std::dynamic_format, the returned value of std::dynamic_format is passed directly on std::basic_format_string as prvalue where copy elision is guaranteed.

auto dynamic_fmt = std::dynamic_format("{}");

auto s0 = std::format(dynamic_fmt, 1); // Error: use of deleted function
auto s1 = std::format(std::move(dynamic_fmt), 1); // still error
auto s2 = std::format(std::dynamic_format("{}"), 1); // OK
Feature-test macro Value Std Feature
__cpp_lib_format 202311L (C++26) Runtime format strings
202603L (C++26) Renaming runtime_format to dynamic_format

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::dynamic_format(fmt), "alpha", 'Z', 3.14, "unused");
    }
}

Output:

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

See also