是否有人建议使用空std::ostringstream来避免使用<<传递给它的参数做任何工作?
这里有两个相关的帖子-- Implementing a no-op std::ostream和Printing to nowhere with ostream,到目前为止最有希望的解决方案是https://stackoverflow.com/a/760353/826203,但是在测试它时
int main() {
onullstream os;
os << 666;
// std::ostringstream & oss = os; // error C2440: 'initializing' : cannot convert from 'onullstream' to 'std::ostringstream &'
oss << "hello, world";
}但是,这只能像os<<666一样使用,但不能用作std::ostringstream &。有办法出去吗?
发布于 2016-10-17 09:51:14
创建非操作流的最简单方法实际上不是创建自定义流类,而是禁用现有流。例如,可以通过将std::ostream的流缓冲区设置为null来禁用其格式化:
std::ostringstream out;
out.std::ostream::rdbuf(0);
// any attempt to write anything to out will fail.如果您需要成功地格式化数据的流,您可以创建一个流缓冲区,它不存储任何字节,并且总是成功的。但是,当使用此流缓冲区时,将执行实际格式设置:
struct nullbuf: std::streambuf {
std::streambuf::int_type overflow(std::streambuf::int_type c) {
return std::char_traits<char>::not_eof(c);
}
};
// ...
nullbuf buf;
std::ostringstream out;
out.std::ostream::rdbuf(&buf);请注意,我还建议而不是让函数使用std::ostringstream作为参数。相反,任何不构造流的函数都应该以std::ostream&的形式运行。如果现有接口已经采用了std::ostringstream,则可以通过从std::ostringstream派生并适当设置流缓冲区来创建空流:
class onullstream
: private virtual nullbuf
, public std::ostringstream {
public:
nullstring()
: std::ios(this)
, std::ostringstgream() {
this->std::ostream::rdbuf(this);
}
};https://stackoverflow.com/questions/40082526
复制相似问题