检查ostream对象是cout还是stream,c ++ [英] Check if ostream object is cout or ofstream, c++
问题描述
在C ++中有一种方法来检查 ostream
对象是 cout
还是 ofstream
object?
Is there a way in C++ to check if an ostream
object is cout
or a ofstream
object?
如下:
ostream& output(ostream& out)
{
if (out == cout)
return out;
else
{
out << "something different because its not going to the console" << endl;
return out;
}
}
我想这样做的原因是想要重载<<
运算符根据使用的流类型做两个不同的事情。
The reason I want to do this, is that I want to overload the <<
operator to do two different things depending on what type of stream it is used with.
是否可以每次使用不同类型的流重载<
Is it possible to just overload the <<
operator twice each time with a different type of stream?
更新以反映意图更好。
推荐答案
可以通过检查流的身份: if(& out ==& cout)...
。
It's possible by checking the stream's 'identity': if ( &out == &cout ) ...
.
但是,我对此测试的用途有疑问。如果你的函数可以处理任何输出流,为什么要考虑使用什么流?
However, I'm in doubt on the usefullness of this test. If your function can handle any output stream, why bother about what stream it is using?
这篇关于检查ostream对象是cout还是stream,c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!