【问题标题】:Why can't I use operator bool() for std::ofstream为什么我不能对 std::ofstream 使用 operator bool()
【发布时间】: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);

http://ideone.com/IhaRaD

我知道std::fstreamoperator bool() 定义为explicit,但我看不出在这种情况下它应该失败的任何原因。没有中间转换,只有临时的std::ofstream 对象和bool。是什么原因?

【问题讨论】:

  • 由于运算符是显式的,并且没有上下文可以隐式转换为 bool,因此您必须显式转换为 bool。:)
  • 显式使其不会转换为布尔值,除非您直接调用 cast。
  • return !! 在这里工作。

标签: c++ c++11 c++14 c++17


【解决方案1】:

正是因为operator bool()被定义为explicit,你不能这样使用它。自动调用explicit operator bool() 的唯一上下文是用于明确的条件,例如if while?:!for 的中间表达式。 (更完整的总结见我的问题When can I use explicit operator bool without a cast?)。

return 语句的值永远不会在上下文中转换为 bool,因此如果要将 std::ofstream 转换为 bool 作为返回值,您必须 em> 使用 static_cast&lt;bool&gt;() 或等效项。

【讨论】:

    【解决方案2】:

    由于运算符被声明为显式,并且没有允许隐式转换为 bool 的上下文(例如在 if 语句中使用),因此您必须将带有流的表达式显式转换为 bool。 例如

    bool touch(const std::string& file_path)
    {
        return bool( std::ofstream(file_path, std::ios_base::app) );
    }
    

    【讨论】:

      【解决方案3】:

      operator bool 的定义如下:

      explicit operator bool() {/*...*/}
      

      注意这里使用了显式,这意味着没有从类到布尔的自动转换。这意味着对于您的代码,您必须这样做:

      #include <fstream>
      #include <string>
      
      bool touch(const std::string& file_path)
      {
          return static_cast<bool>(std::ofstream(file_path, std::ios_base::app));
      }
      
      int main()
      {
          touch("foo.txt");
      }
      

      无论如何,都需要强制转换(最好是static_cast&lt;bool&gt;),因为隐式转换很危险。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-30
        • 2021-03-16
        • 2023-02-02
        • 2018-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多