In this answer I talk about using a std::ifstream
object's conversion to bool
to test whether the stream is still in a good state. I looked in the Josuttis book for more information (p. 600 if you're interested), and it turns out that the iostream
objects actually overload operator void*
. It returns a null pointer when the stream is bad (which can be implicitly converted to false
), and a non-null pointer otherwise (implicitly converted to true
). Why don't they just overload operator bool
?
views:
427answers:
2
+7
A:
It looks like the C++0x standard section 27.4.4.3 has the answer (emphasis mine).
operator unspecified-bool-type() const;
Returns: If
fail()
then a value that will evaluate false in a boolean context; otherwise a value that will evaluate true in a boolean context. The value type returned shall not be convertible toint
.Note: This conversion can be used in contexts where a
bool
is expected (e.g., an if condition); however, implicit conversions (e.g., toint
) that can occur withbool
are not allowed, eliminating some sources of user error.
Kristo
2009-08-26 13:55:54
A:
Because by returning a pointer, than a single hunk of code -- a single function, can be used for both purposes.
Billy3
Billy ONeal
2009-08-26 13:59:28