Why can't I use the bool () operator 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() { touch("foo.txt"); } 

Exit

 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); 

http://ideone.com/IhaRaD

I know that std::fstream operator bool() is defined as explicit , but I see no reason why it should fail in that case. There is no intermediate conversion, only a temporary object std::ofstream and bool . What reason?

+7
source share
3 answers

This is precisely because operator bool() defined as explicit that you cannot use it that way. The only context in which explicit operator bool() is called automatically is for unambiguous conditions, such as if while , ?: , ! and the mean expression for . (For more details, see My question. When can I use an explicit operator bool without a cast? ).

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

+14
source

Since the statement is declared as explicit, and there is no context that allows implicit conversion to bool (such as use in an if expression), you need to explicitly convert the stream expression to bool . for instance

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

The definition of operator bool as follows:

 explicit operator bool() {/*...*/} 

Note the use of explicit here, this means that there is no automatic cast from class to bool. This means that for your code you must do this:

 #include <fstream> #include <string> bool touch(const std::string& file_path) { return static_cast<bool>(std::ofstream(file_path, std::ios_base::app)); } int main() { touch("foo.txt"); } 

Regardless of what casting is required (preferably static_cast<bool> ), due to the implicit conversion being dangerous.

0
source

All Articles