schulmaster
schulmaster

Reputation: 433

C++11 basic_istream conversion to bool

From what I've read, C++11 no longer supports an implicit conversion to void* for istream/ostream, which could then be implicitly converted to bool, for use in while loops etc. For example:

    string test;
    while((getline(cin,test)))
    {
        cout << "received" << endl;

    }
    cout << "break";

The standard now implements an explicit bool operator, so

while(static_cast<bool>(getline(cin,test)))

would be the new standard supported method. However, in both Visual Studio 2017, and GNU g++ with the -std=c++11 flag, both versions compile perfectly. With no implicit pathway to bool from istream supported by the standard, why is this? I can understand VS playing fast and loose with the standard, but GNU too? Thanks for any insight.

Upvotes: 1

Views: 76

Answers (1)

Sneftel
Sneftel

Reputation: 41503

The implicit conversion to void* was removed, but it was replaced by an explicit conversion to bool. Starting in C++11, an explicit cast operator to bool is treated specially. It's known as a "contextual conversion", and can be used implicitly in an expression which naturally expects a boolean value: an if statement condition, a ternary operator's condition, etc.

Upvotes: 3

Related Questions