4

As most know it's not possible to have a standard collection of references. It's also not possible to copy a stream object.

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

I know I can wrap the stream object reference in e.g. a structure, but then you either need to implement the complete interface (if you want to use the wrapper directly as a stream, which I would prefer), or use a public getter function and use that everywhere to get the actual stream.

Is there a simpler way? C++11 solutions are okay.

4

2 回答 2

7

You can't have a container of references, but you can have a container of std::reference_wrapper. Perhaps you want something like:

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

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

于 2013-04-10T11:18:38.477 回答
0

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 pointer and reference-like types this way will only work if you don't need to use streams as polymorphic objects.

于 2013-04-10T16:55:06.863 回答