FrozenHeart FrozenHeart - 5 months ago 38
C++ Question

Why can't I use operator bool() for std::ofstream

Why can't I write the following code?

#include <fstream>
#include <string>

bool touch(const std::string& file_path)
return std::ofstream(file_path, std::ios_base::app);

int main()


prog.cpp: In function 'bool touch(const string&)':
prog.cpp:6:52: error: cannot convert 'std::ofstream {aka std::basic_ofstream<char>}' to 'bool' in return
return std::ofstream(file_path, std::ios_base::app);

I know that
operator bool()
defined as
but I don't see any reason why it should fail in such case. There's no intermediate conversion, just the temporary
object and
. What's the reason?


It's exactly because operator bool() is defined as explicit that you can't use it in this way. The only context where an explicit operator bool() is automatically invoked is for unambiguous conditionals, such as if () while(), ?: and the middle expression of for ().

If you want to convert std::ofstream to bool as a return value, you must use static_cast<bool>() or equivalent.