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...));
设 CharT
对重载 (1,3) 为 char,对重载 wchar_t 为 (2,4)。
这些重载只有在OutputIt
满足概念 std::output_iterator<const CharT&> 时才会参与重载决议。
如果满足以下任意条件,那么行为未定义:
-
OutputIt
未实现 std::output_iterator<const CharT&>。 - 对于
Args
中的某些Ti
,std::formatter<Ti, CharT> 未(按 std::make_format_args 和 std::make_wformat_args 的规定)满足基本格式化器 (BasicFormatter) 的要求。
目录 |
[编辑] 参数
out | - | 指向输出缓冲区的迭代器 | ||||||||||||||||||||||||||||||||||||||||||||||
fmt | - |
每个替换域拥有如下格式:
1) 没有格式说明的替换域
2) 有格式说明的替换域
| ||||||||||||||||||||||||||||||||||||||||||||||
args... | - | 要格式化的实参 | ||||||||||||||||||||||||||||||||||||||||||||||
loc | - | 用于本地环境特定的格式化的 std::locale |
[编辑] 返回值
输出范围末尾后一位置的迭代器。
[编辑] 异常
传播格式化器或迭代器操作所抛的任何异常。
[编辑] 注解
自 P2216R3 起,格式字符串不是常量表达式是错误的。此情况下可使用 std::vformat_to。
[编辑] 示例
运行此代码
#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)..." // < 不使用 ); 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..." // < 不使用 L"...an error!" // < 不使用 ); 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) |
通过输出迭代器写入其实参的格式化表示,不超出指定的大小 (函数模板) |