o.clear(ios :: failbit); o<< F(3); //程序评估f(3)即使它没有必要 int cout; -JKop Dear list,I need to add "disable output" feature to a bunch of objects that outputto ostream (or ofstream). The least intrusive way to do this is passthem ofstream("/dev/null") but this makes my program less portable. Isthere a null ostream built in cpp? Is it easy to implement one?Thanks.Bo 解决方案Yes. Derive a class from std::streambuf and override the protectedvirtual function overflow as followsint overflow(int c) { return c; }Then you can use a standard istream and set its stream buffer to aninstance of your streambuf class using rdbuf. Or you can define yourown derived ostream class which automatically uses an an instance ofyour streambuf class.BTW, Daryle Walker has submitted a null_stream class for inclusion inBoost, which will be reviewed soon. (See http://groups.yahoo.com/group/boost/files/more_io_4.zip. (You have tosign up for the boost developers list to access this: http://www.boost.org/more/mailing_lists.htm#main.) Also, I havewritten an Iostreams Library(http://home.comcast.net/~jturkanis/iostreams/) which allows a nullostream to be defined as follows:struct null_sink : boost::io::sink {void write(const char*, std::streamsize) { }};typedef boost::io::stream_facade<null_sink> null_ostream;JonathanYou can try o.clear(ios::failbit), and then any statement o << 3 will not doanything.You can also set the rdbuf() to NULL in case someone calls o.rdbuf() andwrites to the buffer directly. I''m not sure if the standard allows you tocall o.rdbuf(NULL) though.Disadvantage:o.clear(ios::failbit);o << f(3); // program evaluates f(3) even though it doesn''t have toint cout;-JKop 这篇关于cpp中是否有空ostream(如/ dev / null)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 03:56