std::formatted_size
來自 cppreference.com
定義於標頭檔案 <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, |
(3) | (C++20 起) |
template< class... Args > std::size_t formatted_size( const std::locale& loc, |
(4) | (C++20 起) |
透過根據格式字串 fmt 格式化 args 來確定格式化字串中的總字元數。如果存在,loc 用於特定於區域設定的格式化。
如果 std::formatter<std::remove_cvref_t<Ti>, CharT> 不滿足 Args
中任何 Ti
的 BasicFormatter 要求,則行為未定義。
目錄 |
[編輯] 引數
fmt | - | 表示格式化字串的物件。格式化字串由以下部分組成:
每個替換欄位具有以下格式:
1) 沒有格式化規範的替換欄位
2) 帶有格式化規範的替換欄位
| ||||||||||||||||||||||||||||||||||||||||||||||
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) |
透過輸出迭代器寫出其引數的格式化表示 (函式模板) |
(C++20) |
透過輸出迭代器寫出其引數的格式化表示,不超過指定大小 (函式模板) |