Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 透明地抽象iostream接口_C++_Iostream - Fatal编程技术网

C++ 透明地抽象iostream接口

C++ 透明地抽象iostream接口,c++,iostream,C++,Iostream,对于某些程序,最好有几个流,这样我就可以使用对于任何有的程序,您都可以更改内部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); iostreams是一个抽象接口,这

对于某些程序,最好有几个流,这样我就可以使用
对于任何有
的程序,您都可以更改内部
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);

iostreams是一个抽象接口,这正是它们的设计目的。@user657267那么,如何在运行时从写入文件切换到标准输出,并使用
@Alec,您可以将流的底层缓冲区更改为目标流的缓冲区。@templateboy回答这个问题,如果可行,我会选择它。@Alec听起来您需要一个接受任意流以执行输出,而不是在运行时修改流,您应该包含一些代码以显示您正在尝试执行的操作。您的解决方案工作正常,但在我的情况下,我需要能够在运行时或启动时切换“后端”。例如,仅当在命令中指定时,才将信息流输出到文件,如stdout,否则。啊,我明白了。那么我想你最好用包装器类?我开始发布这种实现作为第二个答案,但我无法很好地编译一个最小的示例。一个大型项目的示例源代码链接是:-尝试在那里搜索“Pout”和“Perr”或“Sout”、“Serr”等术语。这些应该会给你一个想法,但是这个网站并不是非常容易浏览。@Alec
std::ostream o(nullptr)它完美地满足了我的所有需求,谢谢你的明确回答。
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);