【问题标题】:Common parent type ifstream and ofstream常见的父类型 ifstream 和 ofstream
【发布时间】:2012-09-19 11:04:23
【问题描述】:

我有一个包含std::ofstream 和std::ifstream 的类(一次只能激活一个)。我想重载operator() 以返回当前的活动流。但是 std::ofstream 和 std::ifstream 返回公共引用的公共基类型是什么?

【问题讨论】:

  • std::ios,但你真的不能用它做很多事情。
  • This 和 this 可能会有所帮助。

标签: c++ file c++11 stream


【解决方案1】:

输入和输出流是非常不同的类型。它们共享的唯一通用基类是std::ios。除了一些错误检查之外,它并没有太多内容。

这两种流类型只共享最基本的接口。出于显而易见的原因,它们彼此之间几乎没有任何关系。

【讨论】:

  • 我认为他想重载他的 自己的 类'operator() 以返回一些流,并且只希望公共基础知道返回类型是什么。跨度>
【解决方案2】:

我想重载 operator() 以返回当前的活动流 这完全没有意义,而且闻起来像是设计缺陷。你为什么要退货?该运算符的调用者应该能够对返回值做什么?既不能输入也不能输出。

我不知道你真正想做什么,但也许这样的事情对你有用,虽然它很危险

template<typename T> class wrapper
{
  T*const ptr;
  wrapper(T*p) : ptr(p) {}
public:
  bool empty() const { return ptr; }
  operator T& () const
  {
    if(empty()) throw some_exception("trying to use empty wrapper");
    return *ptr;
  }
  friend some_class;
};

class some_class
{
   ifstream _ifstream;
   ofstream _ofstream;
   bool ifstream_is_active;
   bool ofstream_is_active;
public:
   operator wrapper<ifstream> () const
   { wrapper<ifstream>(ifstream_is_active? &_ifstream : 0); }
   operator wrapper<ofstream> () const
   { wrapper<ofstream>(ofstream_is_active? &_ofstream : 0); }
};

但这很危险,因为您可能正在处理悬空指针。您可以通过使用shared_ptr(自己解决)来避免这种情况,但这意味着some_class 不再控制这些流的生命周期。

【讨论】:

  • 异常规范在 C++11 中被弃用(并且在 C++03 中被一些著名的编译器忽略)——最好忽略它们。此外,您不能仅在返回类型上重载函数。
  • @ildjarn 你说得对。我删除了 throw 并纠正了另一个问题(这是一种类型,我打算进行类型转换)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
相关资源
最近更新 更多