为什么我不能编写以下代码?
#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");
}
输出
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);
我知道 std::fstream
的 operator bool()
被定义为 explicit
,但我不清楚它在这种情况下为什么会失败。没有中间转换,只有临时的 std::ofstream
对象和 bool
。是什么原因呢?
return !!
。 - Johannes Schaub - litb