Fro*_*art 7 c++ c++11 c++14 c++17
为什么我不能写下面的代码?
#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");
}
Run Code Online (Sandbox Code Playgroud)
产量
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);
Run Code Online (Sandbox Code Playgroud)
我知道std::fstream的operator bool()定义explicit,但我看不出有任何理由为什么要在这种情况下失败.没有中间转换,只有临时std::ofstream对象和bool.什么原因?
Tob*_*ght 13
这正是因为 operator bool()定义为explicit你不能以这种方式使用它.其中一个唯一的上下文explicit operator bool()被自动调用为条件语句明确,例如if while,?:,!和的中间表达式for.(有关更完整的摘要,请参阅我的问题何时可以在operator bool没有强制转换的情况下使用显式?).
一个return语句的值永远不会上下文转换为bool,所以如果你想转换std::ofstream到bool一个返回值,你必须使用static_cast<bool>()或同等学历.