fmtlib 格式化 基本用法 8—— 扩展stream

12 篇文章 0 订阅

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;
}

运行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值