ZKl*_*ack 2 c++ null stream output
我使用类似的函数
void doStuff(type thing, bool print = false, std::ostream& S = std::cout)
{
thing++;
if(print)
S << "new thing: " << thing << '\n';
}
Run Code Online (Sandbox Code Playgroud)
这样我就可以使用相同的函数并决定调用是否希望它打印正在发生的事情的文档以及如果我希望我可以在单独的流上打印它 - 我不知道我是否可以使用 std:: 来做到这一点奥流-
我现在相信这样做会更好
void doStuff(type thing, std::ostream& S = NULL)
{
thing++;
if(S)
S << "new thing: " << thing << '\n';
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为 std::ostream 不接受 NULL
问题:
- 是否有某种类型的流类型常量可以停止 if 条件?
- 我可以使用更灵活的不同类型的流来接受字符串流和文件流等流吗?
- 有更好的方法来处理灵活的文档吗?
您可以使用库的Null 接收器boost::iostream
。
这是一个工作示例:
#include <iostream>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/null.hpp>
boost::iostreams::stream<boost::iostreams::null_sink> nullstream{boost::iostreams::null_sink()};
void print_to_stream(std::ostream& s = nullstream)
{
s << "hello" << std::endl;
}
int main()
{
std::cout << "calling print_to_stream with s = std::cout" << std::endl;
print_to_stream(std::cout);
std::cout << "calling print_to_stream without argument" << std::endl;
print_to_stream();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可能希望将变量隐藏nullstream
在某些命名空间或类中。