fmtlib主要在 os.h 和 ostream.h中扩展 stream用法。
os.h里扩展 ostream 子类
ostream.h里扩展了 operator << 方法,适配 自定义类型。
主要API
os.h 文件中代码
class fmt::ostream
template<typename ...T>
void print(format_string<T...> fmt, T&&... args)
template<typename ...T>
ostream output_file(cstring_view path, T... params)
提供std::ostream支持,包括格式化具有重载插入运算符(运算符<<)的用户定义类型
为了通过std::ostream生成一个类型formattable,
您应该提供一个继承自ostream_formatter的格式化程序专用化
template<typename T>
auto fmt::streamed(const T &value) -> detail::streamed_view<T>
返回通过ostream运算符格式化值的视图<<
template<typename ...T>
void fmt::print(std::ostream &os, format_string<T...> fmt, T&&... args)
测试 代码:
#include <iostream>
#include <fmt/os.h>
using namespace std;
int main(int argc, char** argv)
{
auto out = fmt::output_file("guide.txt");
out.print("Don't {}", "Panic");
return 0;
}
生成了 guide.txt 文件
测试代码:
#include <iostream>
#include <fmt/ostream.h>
#include <thread>
using namespace std;
struct date
{
int year, month, day;
friend std::ostream& operator<<(std::ostream& os, const date& d) {
return os << d.year << '-' << d.month << '-' << d.day;
}
};
template <> struct fmt::formatter<date> : ostream_formatter {};
int main(int argc, char** argv)
{
std::string s = fmt::format("The date is {}", date{ 2012, 12, 9 });
// s == "The date is 2012-12-9"
cout << s << endl;
fmt::print("Current thread id: {}\n",
fmt::streamed(std::this_thread::get_id()));
fmt::print(cerr, "Don't {}!\n", "panic");
return 0;
}
运行结果