简体   繁体   English

std :: ostringstream如何转换为bool?

[英]How would std::ostringstream convert to bool?

I stumbled across this code. 我偶然发现了这段代码。

    std::ostringstream str;
    /// (some usage)
    assert( ! str );

What does ostringstream signify when used in a bool context? bool上下文中使用时, ostringstream表示什么?

Is this possibly an incorrect usage that happens to compile and run? 这可能是编译和运行时不正确的用法吗?

It tells you if the stream is currently valid. 它会告诉您流是否当前有效。 This is something that all streams can do. 这是所有流可以做的事情。 A file stream, for example, can be invalid if the file was not opened properly. 例如,如果文件未正确打开,则文件流可能无效。

As a side note, this functionality (testing a stream as a bool) is achieved by overloading explicit operator bool in C++11 and later and by overloading the void* cast operator in versions before C++11 . 作为旁注,此功能(将流测试为bool)是通过在C ++ 11及更高版本中重载explicit operator bool 在C ++ 11 之前的版本中重载void* cast运算符来实现的。

Here is a link containing some examples of why a stream might fail . 这是一个链接,其中包含流可能失败的原因的一些示例 This isn't specific to string streams, but it does apply to them. 这不是特定于字符串流,但它确实适用于它们。

Edit: changed bool to void* after Martin York pointed out my mistake. 编辑:在马丁约克指出我的错误后,将bool改为void*

The expression is valid and evaluates the state of the stream. 表达式有效并评估流的状态。 This feature is more commonly used on input streams: 此功能更常用于输入流:

istringstream is;
is.str( "foo" );
int x;
is >> x;

if ( ! is ) {
   cerr << "Conversion failed";
}

I'm not sure how any of the standard streaming functions could cause an ostringstream to go bad, but you could certainly write one yourself. 我不确定任何标准流函数是如何导致ostringstream变坏的,但你当然可以自己写一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM