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.

Community
  • 1
  • 1
Some programmer dude
  • 380,411
  • 33
  • 383
  • 585

2 Answers2

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.

Joseph Mansfield
  • 104,685
  • 19
  • 232
  • 315
  • Just tested and it works fine. Still have to use the `get` function to get the referenced stream if used directly in e.g. output or input operations, but not when passing to other functions. I can live with that. – Some programmer dude Apr 10 '13 at 11:27
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.

bames53
  • 83,021
  • 13
  • 171
  • 237