How to create a collection of stream objects

As you know, it is impossible to have a standard collection of links. It is also not possible to copy a stream object.

But what if I want to make a collection (say, std::vector ) of stream objects or references to a stream object?

I know that I can wrap a link to a stream object, for example. structure, but then you either need to implement the full interface (if you want to use the wrapper directly as a stream, which I would prefer), or use the public getter function and use it everywhere to get the actual stream.

Is there an easier way? C ++ 11 solutions are fine.

+4
source share
2 answers

You do not have a reference container, but you can have a std::reference_wrapper container. Maybe you need something like:

 std::vector<std::reference_wrapper<stream_type>> v; 

You can relate to std::reference_wrapper very much like a link (in fact, it is implicitly converted to a reference type), but it has the additional advantage of being an object type.

+7
source

You can use non-copyable objects in collections:

 // this uses move constructors std::vector<std::fstream> v {std::fstream{"file1.txt"}, std::fstream{"file2.txt"}}; // this doesn't require the type to even be movable v.emplace_back("file3.txt"); 

Although avoiding pointers and reference types, this method will work only if you do not need to use streams as polymorphic objects.

0
source

All Articles