vendredi 2 septembre 2016

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()
{
    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>}' to 'bool' in return
  return std::ofstream(file_path, std::ios_base::app);

http://ift.tt/2c6w9Ea

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

Aucun commentaire:

Enregistrer un commentaire