【发布时间】:2016-09-02 10:57:44
【问题描述】:
为什么我不能写下面的代码?
#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。是什么原因?
【问题讨论】:
-
由于运算符是显式的,并且没有上下文可以隐式转换为 bool,因此您必须显式转换为 bool。:)
-
显式使其不会转换为布尔值,除非您直接调用 cast。
-
return !!在这里工作。