如何扩展std :: basic_streambuf以将任何可迭代序列视为流?

时间:2010-02-03 22:01:36

标签: c++ templates stream sequences

注意:根据回复进行编辑,以获得更合适的答案。

我有多年来制作的C ++模板集合,我称之为Joop。它主要包含那些不完全属于“通用”类别的库,但它们非常有用,我一直将它们打到不同的项目中,所以它们中的大多数都没有其他库中的等价物,例如Boost。

其中一个类是seqstream。这个想法是它允许你将任何可迭代序列视为普通的类STL流,其“字符​​类型”是序列的值类型。

这门课程的理由是双重的。首先,它应该提供一个接口,使任何潜在的非线性,非连续序列看起来是线性和连续的;第二,它应该将流中的任何对象视为单个复杂的大字符。有一种标准的方法可以将流视为一个序列,那么为什么不相反呢?

目前,seqstream为第一个,最后一个和当前元素包装了三个迭代器。我想将seqstream替换为可以插入标准流的basic_seqbuf。任何人都可以提供资源让我开始扩展std::basic_streambuf来提供这种行为吗?

此外,如果允许使用可写seqbuf,那么将对象写入seqbuf 序列化对象是非常正确的,但是要对其进行适当的调用。 insert()方法或使用用户指定的插入迭代器,例如std::back_insert_iterator

修改

以下是当前使用seqstream的示例:

// Create a sequence of objects.
std::vector<std::string> sequence;
for (int i = 0; i < 10; ++i) {
    std::ostringstream stream;
    stream << "Element " << i << ".";
    sequence.push_back(stream.str());
}

// Create a seqstream wrapping that sequence.
joop::seqstream< std::vector<std::string> > seqstream(sequence.begin(), sequence.end());

// Read the sequence like a stream.
std::string element;
while (seqstream >> element) // OR seqstream.get(element)
    std::cout << element << '\n';

1 个答案:

答案 0 :(得分:1)

查看sstream中的示例可能会令人困惑,但您可能根本不需要新的流类。现在查看basic_stringstream源代码的示例,该类的唯一目的是

  • 提供str函数(它只调用底层缓冲区的str
  • 在调用方法时避免使用底层缓冲区的vtable
  • rdbuf的返回值更改为basic_stringbuf*(但这是不必要的,因为提供了str的访问者)

流类的功能很少,除了调用basic_streambuf类型的底层缓冲区之外,它实际上不应具有任何功能。例如,我可以这样做:

string str( "Hello, world!" );
stringbuf buf( str ); // subclass of basic_streambuf
iostream pseudo_stringstream( &buf );
    // pseudo_stringstream can do anything a stringstream can do.
    // (not necessarily with the same syntax)

此外,所有流都应该从basic_istreambasic_ostream或两者继承。如果您的流未正确继承,插入器/提取器函数可能无法正常工作。这些插入器声明非常好:

operator<<( ostream os, MyData d ); // not a template at all
       // templated, but requires correct inheritance:
template< class C > operator<<( basic_ostream<C> os, MyData d );

因此,如果您想要iostream行为,则需要实现basic_streambuf的子类并将其附加到basic_iostream


但是,你的实际目标是什么?内存支持的流优于通常的迭代器以及某些back_insert_iterator的优势是什么?您是否希望使用相同的代码进行序列化以及迭代?您可能希望使用stream_iterator使流看起来像序列,而不是使序列看起来像流。