Search code examples
c++boost-iostreams

C++ iostreams question


I am now diving into boost::iostreams and I'm looking for a way to create a stream that iterates over some container<char>.

Right now I have the code that work for a std::vector<char>, but it does ONLY for it, because I wrote std::vector-specific code.

I am doing the following thing:

template <class Object, class Container>
void Load(Object& object, const Container& container) {

   using namespace boost::iostreams;

   // Create a stream that iterates over vector and use it in
   // the following procedure
   LoadImpl(object, stream<array_source>(&container[0], container.size()));
}

where LoadImpl(...) is described the following way:

template <class Object
void LoadImpl(Object& object, std::istream& stream) { ... }

and is used to wrap serializing / deserializing using some certain stream.

Could you give me any advice on how to make Load routine more generic? Let's say, I would like to have an ability to substitute std::vector<char> to it as long as some std::string container.


Solution

  • Instead of passing the container as a parameter to your functions, what about using the approach taken by the standard library, and use iterators?

    Your function would be templated on the iterator type instead of the container type and would take a begin and end iterator instead of a container. Then it's a simple matter to iterate over the range for any container type you give it.