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

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. (For a more complete summary, see my question When can I use explicit operator bool without a cast?).

A return statement's value is never contextually converted to bool, so if you want to convert std::ofstream to bool as a return value, you must use static_cast<bool>() or equivalent.


As the operator is declared like explicit and there is no context that allows implicit converting to bool (as for example using in the if statement) then you have to convert the expression with the stream to bool explicitly. For example

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