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
It's a cast operator to the given type.
operator T ()
is a cast operator to the type T. In theif
statement, theifstream
is converted tovoid*
, and then thevoid*
converted tobool
.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 anexplicit
conversion tobool
.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
orfor
loop: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. …
However, in some cases even such a verbose structure can be preferable. It depends.
Cheers & hth.,