Why don't iostream objects overload operator bool?

前端 未结 3 1582
無奈伤痛
無奈伤痛 2020-12-06 18:15

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 th

相关标签:
3条回答
  • 2020-12-06 18:25

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

    0 讨论(0)
  • 2020-12-06 18:31

    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.

    0 讨论(0)
  • 2020-12-06 18:43

    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.

    0 讨论(0)
提交回复
热议问题