8

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
SIMEL
  • 8,745
  • 28
  • 84
  • 130
  • 2
    There's a [conversion to bool](http://www.cplusplus.com/reference/ios/ios/operator_bool/), so `return (bool)out != 0;` would compile. But that still seems nonsensical given that the function returns `int`. – Blaze Jan 09 '20 at 10:10
  • Does this answer your question? [Evaluating stream operator >> as boolean](https://stackoverflow.com/questions/41564040/evaluating-stream-operator-as-boolean) – acraig5075 Jan 09 '20 at 11:04

2 Answers2

7

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() returns true, 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).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

There are two operators in the class std::basic_ios that can be applied in such a situation. They are

explicit operator bool() const; 
bool operator!() const; 

So you can for example either write

return bool( out );

or

return !!out;

or

return !out != true;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335