名稱空間
變體
操作

std::basic_format_string, std::format_string, std::wformat_string

來自 cppreference.com
< cpp‎ | 工具庫‎ | 格式化
 
 
 
 
定義於標頭檔案 <format>
template< class CharT, class... Args >
struct basic_format_string;
(1) (C++20 起)
template< class... Args >

using format_string =

    basic_format_string<char, std::type_identity_t<Args>...>;
(2) (C++20 起)
template< class... Args >

using wformat_string =

    basic_format_string<wchar_t, std::type_identity_t<Args>...>;
(3) (C++20 起)

類模板 std::basic_format_string 封裝一個 std::basic_string_view,該物件將由格式化函式使用。

std::basic_format_string 的建構函式在編譯時執行格式字串檢查,除非建構函式引數由 std::runtime_format 返回(C++26 起)

目錄

[編輯] 成員函式

(建構函式)
構造一個 basic_format_string,如果引數不是格式字串,則引發編譯錯誤
(公開成員函式)
get
返回封裝的字串
(公開成員函式)

std::basic_format_string::basic_format_string

template< class T >
consteval basic_format_string( const T& s );
(1)
basic_format_string( /* runtime-format-string */<CharT> s ) noexcept;
(2) (C++26 起)
1) 構造一個 basic_format_string 物件,它儲存字串 s 的檢視。如果引數不是編譯時常量,或者它不能被解析為格式化引數型別 Args 的格式字串,則構造是病態的。
此過載僅當 const T& 滿足 std::convertible_to<std::basic_string_view<CharT>> 模型時才參與過載決議。
2) 構造一個 basic_format_string 物件,它儲存由 std::runtime_format 返回的字串 s 的檢視。它在構造時不執行格式字串檢查。

引數

s - 表示格式化字串的物件。格式化字串由以下部分組成:
  • 普通字元(除了 {}),它們被原樣複製到輸出,
  • 轉義序列 {{}},它們在輸出中分別被替換為 {},以及
  • 替換欄位。

每個替換欄位具有以下格式:

{ arg-id (可選) } (1)
{ arg-id (可選) : format-spec } (2)
1) 沒有格式化規範的替換欄位
2) 帶有格式化規範的替換欄位
arg-id - 指定 args 中用於格式化的引數的索引;如果省略,則按順序使用引數。

格式化字串中的 arg-id 必須全部存在或全部省略。混合手動和自動索引是錯誤的。

format-spec - 由相應引數的 std::formatter 特化定義的格式規範。不能以 } 開頭。

(C++23 起)
(C++26 起)
  • 對於其他可格式化型別,格式化規範由使用者定義的 formatter 特化決定。

std::basic_format_string::get

constexpr std::basic_string_view<CharT> get() const noexcept;

返回儲存的字串檢視。

[編輯] 註記

別名模板 format_stringwformat_string 使用 std::type_identity_t 來禁止模板引數推導。通常,當它們作為函式引數出現時,它們的模板引數是從其他函式引數推匯出來的。

template<class... Args>
std::string format(std::format_string<Args...> fmt, Args&&... args);
 
auto s = format("{} {}", 1.0, 2);
// Calls format<double, int>. Args are deduced from 1.0, 2
// Due to the use of type_identity_t in format_string, template argument deduction
// does not consider the type of the format string.

[編輯] 示例

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
P2508R1 C++20 該功能沒有使用者可見的名稱 公開了名稱 basic_format_string