Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ofstream == NULL won't compile for -std=gnu++11, any workaround?

Tags:

c++

gcc

c++11

stl

Consider the following code:

std::ostream file;
if( file == NULL ) std::cout << "Failed to open file" << std::endl;

It compiles perfectly when passing -std=gnu11 (default from GCC 5.2), or just using
gcc code.cpp -o a.out.

It fails with -std=gnu++11, though:

no match for ‘operator==’ (operand types are ‘std::ofstream {aka std::basic_ofstream<char>}’ and ‘long int’)`

What is the simplest workaround?

Details:

I've got to use std=gnu++11 to have access to shared_ptr definitions. Furthermore, some code of mine is automatically generated and modifying the generator would incur in a reasonable effort - so I was wondering if someone could come up with simpler way to get rid of this "lack of compatibility".

like image 958
rph Avatar asked Sep 15 '15 14:09

rph


1 Answers

The only reason why this ever compiled in the first place is because std::ios, which ofstream derives from, provided a non-explicit(!) operator void* prior to C++11. As of C++11, explicit operator bool is provided instead, which doesn't allow for implicit conversions as necessitated by your code. Instead, write

if (!file) std::cout << "Failed to open file" << std::endl;
like image 87
Columbo Avatar answered Oct 20 '22 06:10

Columbo