Why istream object can be used as a bool expression?

假如想象 提交于 2019-11-26 06:07:00

问题


Does anyone know why istream object can be used as bool expression? For example:

ifstream input(\"tmp\");
int iValue;
while (input >> iValue)
    //do something;

Here input >> iValue returns a reference to the ifstream object. I want to know why this object can be used as a bool expression.
I look into the ifstream class and find that this may be due to the following member function:

operator void * ( ) const;

See here for detail about this function.
If it is, can anyone explain this function to me? The prototype of this function is different from usual operator overload declaration. What is the return type of this function?
If it is not, then what is the reason that ifstream object can be used as bool expression?
Looking forward to your help!

cheng


回答1:


The exact mechanism that enables use of an istream as a boolean expression, was changed in C++11. Previously is was an implicit conversion to void*, as you've found. In C++11 it is instead an explicit conversion to bool.

Use of an istream or ostream in a boolean expression was enabled so that C++ programmers could continue to use an expression with side-effects as the condition of a while or for loop:

SomeType v;

while( stream >> v )
{
    // ...
}

And the reason that programmers do that and want that, is that it gives more concise code, code that is easier to take in at a glance, than e.g. …

for( ;; )
{
    SomeType v;

    stream >> v;
    if( stream.fail() )
    {
        break;
    }
    // ...
}

However, in some cases even such a verbose structure can be preferable. It depends.

Cheers & hth.,




回答2:


It's a cast operator to the given type. operator T () is a cast operator to the type T. In the if statement, the ifstream is converted to void*, and then the void* converted to bool.



来源:https://stackoverflow.com/questions/8117566/why-istream-object-can-be-used-as-a-bool-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!