首页 > 解决方案 > C++;从 std::basic_istream<> 镜像并通过?

问题描述

给定

MyStream派生的类std::basic_istream<>包含指向对象的subject指针std::basic_istream<>。它应响应的相应响应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将告诉、搜索和读取传递给主体,将响应转发给调用者并修改状态标志,以便它们对应于的标志subject

标签: c++istream

解决方案


使用这样的东西:

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::tellghttps://en.cppreference.com/w/cpp/io/basic_istream/tellg) - 它是写的,tellg它将调用rdbuf()->pubseekoff(0, std::ios_base::cur, std::ios_base::in)basic_streambuf::pubseekofhttps://en.cppreference.com/w/cpp/io/basic_streambuf/pubseekoff )的文档提到,它将调用seekoff(off, dir, which). seekoff在课堂上是虚拟的basic_streambuf,你可以覆盖它。


推荐阅读