名稱空間
變體
操作

std::runtime_format

來自 cppreference.com
< cpp‎ | utility‎ | format
 
 
 
 
定義於標頭檔案 <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)s 初始化 str
2) 複製建構函式被顯式刪除。該型別既不可複製也不可移動。
3) 賦值被顯式刪除。

[編輯] 注意

由於 runtime_format 的返回型別既不可複製也不可移動,因此嘗試將 runtime_fmt 作為左值傳遞會阻止 std::basic_format_string 的構造,從而導致程式格式不正確。要使用 runtime_format 構造 std::basic_format_string,將 runtime_format 的返回值直接作為純右值傳遞給 std::basic_format_string,此時保證進行複製省略。

auto runtime_fmt = std::runtime_format("{}");
 
auto s0 = std::format(runtime_fmt, 1); // error
auto s1 = std::format(std::move(runtime_fmt), 1); // still error
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 += "{} "; // constructs the formatting string
        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 的非模板變體
(函式) [編輯]
在構造時執行編譯時格式字串檢查的類模板
(類模板) [編輯]