cheng cheng - 1 month ago 11
C++ Question

Why istream object can be used as a bool expression?

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

Answer

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.,

Comments