透明地抽象iostream接口

transparently abstract a iostream interface

本文关键字:接口 iostream 抽象 透明      更新时间:2023-10-16

对于某些程序,最好有几个流,这样我就可以使用<<运算符提供用于调试的信息、详细信息等

这里的重点是,任何流最终都可以写入文件,通过网络或标准输出进行发送,而最终用户不必知道它,也不必对向流中提供文本的方式进行任何更改。

有了这个解决方案,我希望程序在运行时可以在运行时或启动时(通过命令行参数)从流传输切换到标准输出到文件(例如)。

如何才能最好地做到这一点?

您可以更改内部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样式的包含保护可能是个好主意。

当然,不要选择那些你会被诱惑用来做其他事情的词。