Search code examples
c++booleanistream

Why doesn't this comparison to bool work for an istream?


I have a flimsy understanding of how/why istream can be used in conditionals. I have read this question:(Why istream object can be used as a bool expression?).

I don't understand why this compiles without error…

while (cin >> n) {
    // things and stuff
}

…while this fails to compile (message error: invalid operands to binary expression ('int' and '__istream_type' (aka 'basic_istream<char, std::char_traits<char> >')))

while (true == (cin >> n)) {
    // things and stuff
}

Solution

  • Because the implicit conversion operator of cin is

    operator void*() const { ... }
    

    and it can evaluate to zero, so you can check it against zero

    while (cin >> x) {}
    

    Conversion operator for bool declared as explicit so your expression will not invoke it:

    explicit operator bool(){ ... }
    

    So, you need an explicit cast:

    if (true == static_cast<bool>(cin >> a))
    {
    }