Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 704
cheng Avatar asked Nov 14 '11 05:11

cheng


2 Answers

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.

like image 70
Cheers and hth. - Alf Avatar answered Sep 20 '22 17:09

Cheers and hth. - Alf


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.

like image 33
Puppy Avatar answered Sep 20 '22 17:09

Puppy