【问题标题】:C++; mirror and pass through from std::basic_istream<>?C++;从 std::basic_istream<> 镜像并通过?
【发布时间】:2019-10-29 16:47:56
【问题描述】:

给定

std::basic_istream&lt;&gt; 派生的类MyStream 包含指向std::basic_istream&lt;&gt; 对象的指针subject。它应对tellg()read() 响应subject 相应响应的修改内容。

template <class T> MyStream :
   public std::basic_istream<typename T::char_type, typename T::traits_type> {

   std::basic::istream<...>*   subject;

   ...
};

问题:函数tellg()seekg()read() 以及状态标志函数不是虚函数。

问题MyStream 对象如何将告诉、查找和读取传递给主体,将响应转发给调用者并修改状态标志,使其与 @987654335 的标志相对应@?

【问题讨论】:

标签: c++ istream


【解决方案1】:

使用这样的东西:

template <typename T> struct MyStream : public std::basic_istream<typename T::char_type, typename T::traits_type> {
   struct rdbuf_impl : public std::basic_streambuf<typename T::char_type, typename T::traits_type> {
       // overwrite what you need
       std::basic::istream<...>* subject;

       // for tellg passthru (an example)
       pos_type seekoff( off_type off, std::ios_base::seekdir dir,
                      std::ios_base::openmode which = ios_base::in | ios_base::out ) overwrite {
           return subject->pubseekoff(off, dir, which);
       }
   };
   MyStream(std::basic::istream<...>* subject) {
       auto v = new rdbuf_impl(subject);
       rdbuf(v); // set associated stream buffer 'v' in 'this'.
   }
};

编辑: 让我们考虑tellg 方法。查看类basic_istream::tellg (https://en.cppreference.com/w/cpp/io/basic_istream/tellg) 的定义 - 写的是tellg 将调用rdbuf()-&gt;pubseekoff(0, std::ios_base::cur, std::ios_base::in)basic_streambuf::pubseekof (https://en.cppreference.com/w/cpp/io/basic_streambuf/pubseekoff) 的文档提到,它将调用 seekoff(off, dir, which)seekoffbasic_streambuf 类中是虚拟的,你可以覆盖它。

【讨论】:

  • 请您详细说明您的解决方案吗?如何将电话转接到tellg() 等到subjectsubject 的状态如何反映在 MyStream 的状态位中?
  • 抱歉,我取消了复选标记,因为我仍然看不到如何处理标志和read() 函数。目前它似乎非常复杂。为什么我需要一个缓冲区并且没有中间存储就无法传递数据?
  • 您说的问题,tellg 和朋友不是虚拟的以及如何传递信息。我以解决tellg 问题的示例的形式为您提供了解决方案。其他类似解决。由于 C++ 库的设计,它很复杂,如果不是更老的话,也有 20 年的历史。
  • 这是一种苦药,但我想我必须吞下它——你说得对。 (40 年前就有了奇妙的库设计,所以 I/O 库开发人员没有任何借口……或者,我可能错过了精彩之处)。
猜你喜欢
  • 1970-01-01
  • 2014-05-24
  • 2022-09-28
  • 2017-09-29
  • 2020-10-17
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多