为什么我不能对std :: ofstream使用运算符bool() [英] 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");
}
输出
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
运算符bool()
定义为 explicit
,但我看不出在这种情况下失败的任何原因。没有中间转换,只有临时 std :: ofstream
对象和 bool
。是什么原因?
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?
推荐答案
正是因为 运算符bool()
被定义为 explicit
,您不能以这种方式使用它。自动调用显式运算符bool()
的唯一上下文是明确的条件,例如 if
while
,?:
,!
和<$ c的中间表达式$ c>用于。 (有关更完整的摘要,请参阅我的问题何时可以在不进行强制转换的情况下使用显式 operator bool
?)
It's exactly because operator bool()
is defined as explicit
that you can't use it in this way. The only context where an explicit operator bool()
is automatically invoked is for unambiguous conditionals, such as if
while
, ?:
, !
and the middle expression of for
. (For a more complete summary, see my question When can I use explicit operator bool
without a cast?).
返回
语句的值永远不会上下文转换为 bool
,因此,如果要将 std :: ofstream
转换为 bool
返回值,您必须使用 static_cast< bool>()
或等效值。
A return
statement's value is never contextually converted to bool
, so if you want to convert std::ofstream
to bool
as a return value, you must use static_cast<bool>()
or equivalent.
这篇关于为什么我不能对std :: ofstream使用运算符bool()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!