std::format_to
來自 cppreference.com
定義於標頭檔案 <format> |
||
template< class OutputIt, class... Args > OutputIt format_to( OutputIt out, |
(1) | (C++20 起) |
template< class OutputIt, class... Args > OutputIt format_to( OutputIt out, |
(2) | (C++20 起) |
template< class OutputIt, class... Args > OutputIt format_to( OutputIt out, const std::locale& loc, |
(3) | (C++20 起) |
template< class OutputIt, class... Args > OutputIt format_to( OutputIt out, const std::locale& loc, |
(4) | (C++20 起) |
根據格式字串 fmt 格式化 args,並將結果寫入輸出迭代器 out。如果存在,loc 用於本地化特定格式。
等價於
1) return std::vformat_to(std::move(out), fmt.str, std::make_format_args(args...));
2) return std::vformat_to(std::move(out), fmt.str, std::make_wformat_args(args...));
3) return std::vformat_to(std::move(out), loc, fmt.str, std::make_format_args(args...));
4) return std::vformat_to(std::move(out), loc, fmt.str, std::make_wformat_args(args...));。
對於過載 (1,3),令 CharT
為 char;對於過載 (2,4),令 CharT
為 wchar_t。
這些過載僅當 OutputIt
滿足概念 std::output_iterator<const CharT&> 時才參與過載決議。
如果滿足以下任何條件,則行為是未定義的:
-
OutputIt
不符合 std::output_iterator<const CharT&> 模型。 - 對於
Args
中的某些Ti
,std::formatter<Ti, CharT> 不滿足 BasicFormatter 要求(如 std::make_format_args 和 std::make_wformat_args 所要求)。
目錄 |
[編輯] 引數
out | - | 指向輸出緩衝區的迭代器 | ||||||||||||||||||||||||||||||||||||||||||||||
fmt | - |
每個替換欄位具有以下格式:
1) 沒有格式化規範的替換欄位
2) 帶有格式化規範的替換欄位
| ||||||||||||||||||||||||||||||||||||||||||||||
args... | - | 要格式化的引數 | ||||||||||||||||||||||||||||||||||||||||||||||
loc | - | 用於特定於語言環境的格式化的 std::locale |
[編輯] 返回值
輸出範圍末尾之後的迭代器。
[編輯] 異常
傳播由格式化器或迭代器操作丟擲的任何異常。
[編輯] 注意
根據 P2216R3,如果格式字串不是常量表達式,則會出錯。std::vformat_to 或 std::runtime_format(C++26起) 可用於此情況。
[編輯] 示例
執行此程式碼
#include <format> #include <iostream> #include <iterator> #include <string> int main() { std::string buffer; std::format_to ( std::back_inserter(buffer), // < OutputIt "Hello, C++{}!\n", // < fmt "20" // < arg ); std::cout << buffer; buffer.clear(); std::format_to ( std::back_inserter(buffer), // < OutputIt "Hello, {0}::{1}!{2}", // < fmt "std", // < arg {0} "format_to()", // < arg {1} "\n", // < arg {2} "extra param(s)..." // < unused ); std::cout << buffer << std::flush; std::wstring wbuffer; std::format_to ( std::back_inserter(wbuffer),// < OutputIt L"Hello, {2}::{1}!{0}", // < fmt L"\n", // < arg {0} L"format_to()", // < arg {1} L"std", // < arg {2} L"...is not..." // < unused L"...an error!" // < unused ); std::wcout << wbuffer; }
輸出
Hello, C++20! Hello, std::format_to()! Hello, std::format_to()!
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3539 | C++20 | out 不能是僅移動迭代器 | 它可以是 |
P2216R3 | C++20 | 對無效格式字串丟擲 std::format_error | 導致編譯時錯誤 |
P2418R2 | C++20 | 既不可 const 使用也不可複製的物件 (例如生成器類物件) 不可格式化 |
允許格式化這些物件 |
P2508R1 | C++20 | 該功能沒有使用者可見的名稱 | 公開了名稱 basic_format_string |
[編輯] 另請參閱
(C++20) |
將引數的格式化表示儲存在新字串中 (函式模板) |
(C++20) |
透過輸出迭代器寫出其引數的格式化表示,不超過指定大小 (函式模板) |