C++;镜像并从 std::basic_istream<> 穿过?

C++; mirror and pass through from std::basic_istream<>?

给定

std::basic_istream<> 派生的 class MyStream 包含指向 std::basic_istream<> 对象的指针 subject。它应使用从 subject 的相应响应中修改的内容来响应 tellg()read()

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

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

   ...
};

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

问题MyStream 对象如何将 tell、seek 和 read 传递给主题,将响应转发给调用者并修改状态标志,以便它们对应于subject的标志?

使用这样的东西:

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 方法。查看 class basic_istream::tellg (https://en.cppreference.com/w/cpp/io/basic_istream/tellg) - it is written, that tellg will call rdbuf()->pubseekoff(0, std::ios_base::cur, std::ios_base::in). Documentation for basic_streambuf::pubseekof (https://en.cppreference.com/w/cpp/io/basic_streambuf/pubseekoff) 提到的定义,它将调用 seekoff(off, dir, which)seekoffbasic_streambuf class 中是虚拟的,你可以覆盖它。