why can't write 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"); } output
prog.cpp: in function 'bool touch(const string&)': prog.cpp:6:52: error: cannot convert 'std::ofstream {aka std::basic_ofstream<char>}' 'bool' in return return std::ofstream(file_path, std::ios_base::app); i know std::fstream's operator bool() defined explicit don't see reason why should fail in such case. there's no intermediate conversion, temporary std::ofstream object , bool. what's reason?
it's exactly because operator bool() defined explicit can't use in way. context explicit operator bool() automatically invoked unambiguous conditionals, such if () while(), ?: , middle expression of for ().
if want convert std::ofstream bool return value, must use static_cast<bool>() or equivalent.
Comments
Post a Comment