当前位置:网站首页>std::format格式化自定义类型
std::format格式化自定义类型
2022-08-11 01:07:00 【windSnowLi】
示例代码
#include <string>
#include <iostream>
// 导入format
#include <format>
struct Vector4D
{
int x, y, z, s;
};
// std::formatter格式化Vector4D
namespace std {
template <>
class formatter<Vector4D> {
public:
explicit formatter() noexcept
: _fmt(OutputFormat::XYZS)
{
}
typename std::basic_format_parse_context<char>::iterator
parse(std::basic_format_parse_context<char>& pc) {
if (pc.begin() == pc.end() || *pc.begin() == '}') {
_fmt = OutputFormat::XYZS;
return pc.end();
}
switch (*pc.begin()) {
case 'X':
_fmt = OutputFormat::X;
break;
case 'Y':
_fmt = OutputFormat::Y;
break;
case 'Z':
_fmt = OutputFormat::Z;
break;
case 'S':
_fmt = OutputFormat::S;
default:
throw std::format_error("Invalid format specification");
}
return pc.begin() + 1;
}
template <typename OutputIt>
std::basic_format_context<OutputIt, char>::iterator
format(const Vector4D& value, std::basic_format_context<OutputIt, char>& fc) const noexcept {
std::string valueString;
switch (_fmt) {
case OutputFormat::XYZS: {
valueString = std::format("X={}, Y={}, Z={}, S={}",
value.x, value.y, value.z, value.s);
break;
}
case OutputFormat::X:
valueString = std::format("X={}", value.x);
break;
case OutputFormat::Y:
valueString = std::format("Y={}", value.y);
break;
case OutputFormat::Z:
valueString = std::format("Z={}", value.z);
break;
case OutputFormat::S:
valueString = std::format("S={}", value.s);
break;
}
auto output = fc.out();
for (auto ch : valueString) {
*output++ = ch;
}
return output;
}
private:
enum class OutputFormat {
X,
Y,
Z,
S,
XYZS
};
OutputFormat _fmt;
};
} // namespace std
int main()
{
Vector4D v = {
1, 2, 3, 4 };
std::cout << std::format("{}", v) << std::endl;
return 0;
}
边栏推荐
猜你喜欢
如何破坏Excel文件,让其显示文件已损坏方法
使用 BeanUtils 做属性拷贝,性能有点拉胯!
容器技术真的是环境管理的救星吗?
两个链表的第一个公共节点——LeetCode
【C语言】探索数据的存储(整形篇)
[Server data recovery] Data recovery case of lvm information and VXFS file system corruption caused by raid5 crash
rhel7.0解决yum无法使用(system is not registered to Red Hat Subscription Management)
#yyds Dry Goods Inventory#[Yugong Series] August 2022 Go Teaching Course 008-Integer of Data Types
还在用 Xshell?你 out 了,推荐一个更现代的终端连接工具,好用到爆!
SQL statement--get database table information, table name, column name, description comment, etc.
随机推荐
[GXYCTF2019]BabySQli
Jvm. Profiling tools (jconsole, jvisualvm, arthas, jprofiler, mat)
HW-蓝队工作流程(1)
【redis】发布和订阅消息
MySQL索引与事务
构建检测,无规矩不成方圆
什么是数组
@Autowired注入RedisCache报错空指针
微信小程序自定义navigationBar
Ambari迁移Spark2到其它机器(图文教程)
"NIO Cup" 2022 Nioke Summer Multi-School Training Camp 3 DF Problem Solving
分库分表ShardingSphere-JDBC笔记整理
Data Analysis Interview Manual "SQL"
使用 BeanUtils 做属性拷贝,性能有点拉胯!
vim simple save window id
③ 关系数据库标准语言SQL 数据查询(SELECT)
微信小程序通过URL Scheme动态的渲染数据
【mysql】mysql分别按年/月/日/周分组统计数据
① 数据库介绍 及 关系型数据库的关系代数表达式
20张图,全面掌握MVCC原理!