速速感恩吧,因为C++20引入了< format >
这东西原来是属于github上的一个开源库fmtlib/fmt,后来被弄进了标准库,也算好事一桩了。
但是丑话说在前头,在我动笔这时候gcc(12)还没有编写< format>,而且可能永远不会编写了....参考
所以接下来我使用的工具链是vs2022提供的
使用方法
#include<iostream>
#include<format>
int main(){
std::cout<<std::format("1+1={}",2);
}
>1+1=2
是不是很有趣啊哈哈哈哈
让std::format支持自定义类型,跟着我操作就完事了
struct mStruct
{
int a;
std::string b;
bool c;
};
//这里的_CharT可以省略
template<typename _CharT>
//因为formatter里指定过_CharT=char
//我估计这是用来适配不同的字符类型的
//还是留着为好
struct std::formatter<mStruct, _CharT> : std::formatter<int, _CharT>
{
template<typename Context>
//返回值其实是typename Context::iterator
//可是我懒哈哈哈
auto format(const mStruct& m, Context& context) {
//注:typename消除歧义
typename Context::iterator Iter = std::formatter<int, _CharT>().format(m.a, context);
Iter = '\n';
Iter = std::formatter<string, _CharT>().format(m.b, context);
Iter = '\n';
Iter = std::formatter<bool, _CharT>().format(m.c, context);
return Iter;
}
};
template<class T>
struct mStruct2
{
int a;
std::string b;
bool c;
T d;
};
template<typename T>
struct std::formatter<mStruct2<T>> : std::formatter<int>
{
template<typename Context>
auto format(const mStruct2<T>& m, Context& context) {
typename Context::iterator Iter = std::formatter<int>().format(m.a, context);
Iter = '\n';
Iter = std::formatter<string>().format(m.b, context);
Iter = '\n';
Iter = std::formatter<bool>().format(m.c, context);
Iter = '\n';
Iter = std::formatter<T>().format(m.d, context);
return Iter;
}
};
还有自定义精度什么的,太多了,不列出来了
去这里看看吧