透明地抽象iostream接口
transparently abstract a iostream interface
对于某些程序,最好有几个流,这样我就可以使用<<
运算符提供用于调试的信息、详细信息等
这里的重点是,任何流最终都可以写入文件,通过网络或标准输出进行发送,而最终用户不必知道它,也不必对向流中提供文本的方式进行任何更改。
有了这个解决方案,我希望程序在运行时可以在运行时或启动时(通过命令行参数)从流传输切换到标准输出到文件(例如)。
如何才能最好地做到这一点?
您可以更改内部std::streambuf
指针以指向目标输出流:
std::streambuf* p = std::cerr.rdbuf(nullptr);
o.rdbuf(p);
// Do what you want with the output stream o which now has std::cerr.rdbuf()
// Reset
std::cerr.rdbuf(p);
对于任何定义了<<
运算符的东西,如果您愿意,您可以为它们设置#define
关键字?例如:
ofstream myLogFile("/path/to/my/logFile");
#define Info std::cout
#define Err std::cerr
#define Log myLogFile
Info << "Send this message to cout" << std::endl;
Err << "Send this message to cerr" << std::endl;
Log << "Send this message to my logfile at /path/to/my/logFile" << std::endl;
我认为这就是你想要的——当然,这可以包含在一个标题中,前提是你在使用它们之前放置了包含。在这种情况下,#ifndef
样式的包含保护可能是个好主意。
当然,不要选择那些你会被诱惑用来做其他事情的词。
相关文章:
- 是否可以用"iostream"包装现有的TCP/OOpenSSL会话
- 需要从 istream 和 ostream 派生 iostream
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- Visual C++GC接口如何启用它以及要包含哪个库
- Windows.h与GLFW.h的接口
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 提供与TMP和SFINAE的通用接口
- 为重写std::exception的库生成swig接口时出错
- 内联如何影响模块接口中的成员函数
- std::带有自定义缓冲区的 iostream 不允许我写入
- COM 接口 c# 封送数组数组
- 如何在 SCIP C++ 接口中获取 MILP 约束矩阵中的系数值
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 如何绑定 C++ gRPC 客户端的网络接口
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 如何从实现接口的模板化类实例访问结构
- 新的放置取决于 iostream
- 带有进度表的 curl 多接口程序
- 包含在 <initializer_list> <iostream>?
- 透明地抽象iostream接口