名稱空間
變體
操作

std::formatted_size

來自 cppreference.com
< cpp‎ | 工具‎ | 格式化
 
 
 
 
定義於標頭檔案 <format>
template< class... Args >
std::size_t formatted_size( std::format_string<Args...> fmt, Args&&... args );
(1) (C++20 起)
template< class... Args >
std::size_t formatted_size( std::wformat_string<Args...> fmt, Args&&... args );
(2) (C++20 起)
template< class... Args >

std::size_t formatted_size( const std::locale& loc,

                            std::format_string<Args...> fmt, Args&&... args );
(3) (C++20 起)
template< class... Args >

std::size_t formatted_size( const std::locale& loc,

                            std::wformat_string<Args...> fmt, Args&&... args );
(4) (C++20 起)

透過根據格式字串 fmt 格式化 args 來確定格式化字串中的總字元數。如果存在,loc 用於特定於區域設定的格式化。

如果 std::formatter<std::remove_cvref_t<Ti>, CharT> 不滿足 Args 中任何 TiBasicFormatter 要求,則行為未定義。

目錄

[編輯] 引數

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

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

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

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

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

(C++23 起)
(C++26 起)
  • 對於其他可格式化型別,格式化規範由使用者定義的 formatter 特化決定。
args... - 要格式化的引數
loc - 用於特定於語言環境的格式化的 std::locale

[編輯] 返回值

格式化字串中的總字元數。

[編輯] 異常

傳播格式化器丟擲的任何異常。

[編輯] 示例

#include <format>
#include <iomanip>
#include <iostream>
#include <string_view>
#include <vector>
 
int main()
{
    using namespace std::literals::string_view_literals;
 
    constexpr auto fmt_str{"Hubble's H{0} {1} {2:*^4} miles/sec/mpc."sv};
    constexpr auto sub_zero{"\N{SUBSCRIPT ZERO}"sv}; // "₀" or {0342, 130, 128}
    constexpr auto aprox_equ{"\N{APPROXIMATELY EQUAL TO}"sv}; // "≅" or {0342, 137, 133}
    constexpr int Ho{42}; // H₀
 
    const auto min_buffer_size{std::formatted_size(fmt_str, sub_zero, aprox_equ, Ho)};
    std::cout << "Min buffer size = " << min_buffer_size << '\n';
 
    // Use std::vector as dynamic buffer. The buffer does not include the trailing '\0'.
    std::vector<char> buffer(min_buffer_size);
 
    std::format_to_n(buffer.data(), buffer.size(), fmt_str, sub_zero, aprox_equ, Ho);
    std::cout << "Buffer: "
              << std::quoted(std::string_view{buffer.data(), min_buffer_size})
              << '\n';
 
    // Print the buffer directly after adding the trailing '\0'.
    buffer.push_back('\0');
    std::cout << "Buffer: " << std::quoted(buffer.data()) << '\n';
}

輸出

Min buffer size = 37
Buffer: "Hubble's H₀ ≅ *42* miles/sec/mpc."
Buffer: "Hubble's H₀ ≅ *42* miles/sec/mpc."

[編輯] 缺陷報告

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

缺陷報告 應用於 釋出時的行為 正確的行為
P2216R3 C++20 對無效格式字串丟擲 std::format_error 無效格式字串導致編譯時錯誤
P2418R2 C++20 既不可 const 使用也不可複製的物件
(例如生成器類物件) 不可格式化
允許格式化這些物件
P2508R1 C++20 該功能沒有使用者可見的名稱 公開了名稱 basic_format_string

[編輯] 另請參閱

(C++20)
透過輸出迭代器寫出其引數的格式化表示
(函式模板) [編輯]
透過輸出迭代器寫出其引數的格式化表示,不超過指定大小
(函式模板) [編輯]