I'm upgrading existing old code to use VS 2019*, in the code I have the following function that fails on the return line:
int foo(const char *fn) const
{
ofstream out(fn,ios::binary);
if (out)
{
//...
}
return out!=0;
}
The error I get is:
Error C2678 binary '!=': no operator found which takes a left-hand operand of type 'std::ofstream' (or there is no acceptable conversion)
What was the original poet's intention, and what is the best way to fix the issue?
*This code compiles successfully on VS 2010.
I suppose with the upgrading, you're switching to C++11 mode.
Before C++11, std::basic_ios
(the base class of std::basic_ofstream
) could convert to void*
implicitly.
Returns a null pointer if
fail()
returnstrue
, otherwise returns a non-null pointer.
Then out!=0
is checking whether the stream has no errors and is ready for further I/O operations.
Since C++11, there's only one conversion operator which could convert std::basic_ios
to bool
. Note that the operator is marked as explicit
, so the implicit conversion isn't allowed for out!=0
.
You can change the code to !!out
(invoking operator!
), or !out.fail()
, or static_cast<bool>(out)
(explicit conversion via operator bool
).