Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

The following code compiles in Visual Studio 2008 but fails in Visual Studio 2013 and later.

std::string str("foo");
std::stringstream ss(str);
float f = 0;

if ((ss >> f) == false)
    std::cout << "Parse error\n";

The error message is

error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::basic_istream>' (or there is no acceptable conversion)

and is successfully fixed by changing as follows:

if (!(ss >> f))
    std::cout << "Parse error\n";

I'm not understanding this well. My question is, what operator or cast or maybe ios flags are involved that allow the stream read to be evaluated as a boolean in the first place, and then why does the lack of an operator== break it?

share|improve this question
up vote 14 down vote accepted

Two behaviors changed since C++11.

1. The behavior of std::basic_ios::operator bool changed.

operator void*() const;         (1) (until C++11)
explicit operator bool() const; (2) (since C++11)

Note since C++11 operator bool() is declared as explicit; but for if ((ss >> f) == false), ss (i.e. the return value of (ss >> f)) needs to be implicit converted to bool (to be compared with false), which is not allowed.

2. The definition of NULL (the null pointer constant) changed.

Before C++11 operator void*() could be used and it's not explicit (before C++11 there's no such thing like explicit user-defined conversion), and before C++11 NULL (the null pointer constant) is defined as

an integral constant expression rvalue of integer type that evaluates to zero (until C++11)

which means false could be used as a null pointer constant. So ss could be implicitly converted to void* and then compared with false (as the null pointer).

From C++11 NULL is defined as

an integer literal with value zero, or a prvalue of type std::nullptr_t (since C++11)

while false is not again; it's not an integer literal.

So from these two changes, after C++11 if ((ss >> f) == false) won't work again.

On the other hand, if (!(ss >> f)) works fine because there's std::basic_ios::operator! (both before and after C++11) for it.

bool operator!() const;

Returns true if an error has occurred on the associated stream. Specifically, returns true if badbit or failbit is set in rdstate().

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.