Namespaces
Variants

std:: runtime_format

From cppreference.net
ヘッダーで定義 <format>
/*runtime-format-string*/ < char > runtime_format ( std:: string_view fmt ) noexcept ;
(1) (C++26以降)
/*runtime-format-string*/ < wchar_t > runtime_format ( std:: wstring_view fmt ) noexcept ;
(2) (C++26以降)

ユーザー向け書式設定関数で直接使用可能な実行時書式文字列を格納するオブジェクトを返し、 std::basic_format_string への暗黙変換が可能です。

目次

パラメータ

fmt - 文字列ビュー

戻り値

説明専用の型の実行時フォーマット文字列を保持するオブジェクト:

クラステンプレート runtime-format-string <CharT>

template < class CharT >
struct /*runtime-format-string*/ ;
( 説明専用* )

メンバオブジェクト

返されるオブジェクトは、説明専用の非静的データメンバ str を保持します。その型は std::basic_string_view<CharT> です。

コンストラクタと代入演算子

/*runtime-format-string*/ ( std:: basic_string_view < CharT > s ) noexcept ;
(1)
/*runtime-format-string*/ ( const /*runtime-format-string*/ & ) = delete ;
(2)
/*runtime-format-string*/ & operator = ( const /*runtime-format-string*/ & ) = delete ;
(3)
1) str s で初期化します。
2) コピーコンストラクタは明示的に削除されています。この型はコピーもムーブもできません。
3) 代入演算子は明示的に削除されています。

注記

runtime_format の戻り値の型はコピーもムーブもできないため、 runtime_fmt をglvalueとして渡そうとすると、 std::basic_format_string の構築が阻害され、プログラムは不適格となる。 runtime_format std::basic_format_string を構築するには、 runtime_format の戻り値を std::basic_format_string にprvalueとして直接渡す必要があり、この場合コピー省略が保証される。

auto runtime_fmt = std::runtime_format("{}");
auto s0 = std::format(runtime_fmt, 1); // エラー
auto s1 = std::format(std::move(runtime_fmt), 1); // 依然としてエラー
auto s2 = std::format(std::runtime_format("{}"), 1); // OK
機能テスト マクロ 標準 機能
__cpp_lib_format 202311L (C++26) 実行時フォーマット文字列

#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 += "{} "; // フォーマット文字列を構築
        std::print("{} : ", fmt);
        std::println(std::runtime_format(fmt), "alpha", 'Z', 3.14, "unused");
    }
}

出力:

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

関連項目

(C++20)
引数の書式化された表現を新しい文字列に格納する
(関数テンプレート)
(C++20)
std::format の非テンプレート版(型消去された引数表現を使用)
(関数)
構築時にコンパイル時フォーマット文字列チェックを実行するクラステンプレート
(クラステンプレート)