标准无操作输出流 [英] Standard no-op output stream

查看:117
本文介绍了标准无操作输出流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法创建一个基本上不做任何事情的ostream实例?



例如:

  std :: ostream dummyStream(...); 
dummyStream<< 没有什么会打印;

我可以创建一个ostringstream,但是数据将被缓冲(我真的不想任何想法?



[ edit] 找到此相关问题 a>适合我的需要。但是,我认为可能有一个答案,说如何使用标准c ++创建一个有效的(无badbit)输出流。

您需要一个自定义的streambuf。

  class NullBuffer:public std :: streambuf 
{
public:
int overflow int c){return c; }
};

然后,您可以在任何ostream类中使用此缓冲区

  NullBuffer null_buffer; 
std :: ostream null_stream(& null_buffer);
null_stream<< 没有什么会打印;

streambuf :: overflow 当缓冲区必须输出数据到流的实际目的地。当调用溢出时, NullBuffer 类不会产生任何输出,所以任何使用它的流都不会产生任何输出。


Is there a way to create an ostream instance which basically doesn't do anything ?

For example :

std::ostream dummyStream(...);
dummyStream << "Nothing will be printed";

I could just create an ostringstream, but data will be buffered (and I really don't want to make anything with them, so it adds a useless overhead).

Any idea ?

[edit] Found this related question which suits my needs. However, I think it could be useful to have a answer saying how to create a valid (no badbit) output stream with standard c++.

解决方案

You need a custom streambuf.

class NullBuffer : public std::streambuf
{
public:
  int overflow(int c) { return c; }
};

You can then use this buffer in any ostream class

NullBuffer null_buffer;
std::ostream null_stream(&null_buffer);
null_stream << "Nothing will be printed";

streambuf::overflow is the function called when the buffer has to output data to the actual destination of the stream. The NullBuffer class above does nothing when overflow is called so any stream using it will not produce any output.

这篇关于标准无操作输出流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆