9

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?

Community
  • 1
  • 1
Michael Kristofik
  • 34,290
  • 15
  • 75
  • 125

3 Answers3

13

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 to int.

Note: This conversion can be used in contexts where a bool is expected (e.g., an if condition); however, implicit conversions (e.g., to int) that can occur with bool are not allowed, eliminating some sources of user error.

Michael Kristofik
  • 34,290
  • 15
  • 75
  • 125
8

This is an instance of the "safe bool" problem.

Here is a good article: http://www.artima.com/cppsource/safebool.html .

C++0x helps the situation with explicit conversion functions, as well as the change that Kristo mentions. See also Is the safe-bool idiom obsolete in C++11? .

Community
  • 1
  • 1
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
0

The newest C++11 requires that:

explicit operator bool() const;

See C++11 27.5.5.4-1. The 'explicit' seems odd to me, though.

Lingxi
  • 14,579
  • 2
  • 37
  • 93
  • 1
    `explicit` is the reason it was added. An `explicit` conversion function such as this will only apply if it is the *only* conversion, in this case it will convert `iostream` to `bool` but not to `int` via an intermediate `bool` conversion. Read the other answers on this page to learn about the Safe Bool Idiom. – Potatoswatter May 15 '12 at 06:54