c++ - 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
?
解决方案
使用这样的东西:
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()->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)
. seekoff
在课堂上是虚拟的basic_streambuf
,你可以覆盖它。
推荐阅读
- kubernetes - 当 pod 在多个节点上运行时,在 EKS 上出现间歇性超时
- amazon-web-services - 如何使用 ServiceAccount 创建 AWS IAM 角色并附加到 Kubernetes DaemonSet
- python - Tensorflow:google colab上的对象检测api错误-没有名为lvis的模块
- swift - MacOS 通用链接未在 AppDelegate 中运行预期功能
- r - 使用来自 Blynk Server 的数据在 R 中自动化月度报告
- tarantool - 如何自动配置 Tarantool Cartridge 集群?
- ios - 如何像我提供的示例一样创建(集合?)视图
- status - 如何将 Rundeck 作业的步骤状态获取到文件中
- kubernetes - Kubernetes 上带有气流的 Vault
- ruby-on-rails - 如何修复带有链接的渲染提及(例如“@test @test2”)但@test2 链接到@test 的页面