Can I make std::pair of two std::ostream-s?

Viewed 153

I'd like to make a pair containing two std::ostream object. I need this so that I can pass a single object to various functions instead of two std::ostream objects. I was hoping I could do this:

#include <iostream>
#include <ostream>

using namespace std;

int main(){

    std::ostream output( std::cout.rdbuf());
    std::ostream error(std::cout.rdbuf());

    using Logger = std::pair< std::ostream, std::ostream >;
    Logger logger = std::make_pair( output, error );

  return 0;
}

But I get a compiler error that there isn't a matching constructor for pair<std::basic_ostream<char>, std::basic_ostream<char> >

2 Answers

The problem that you’re having is that ostream can’t be copied.
The solution is to use a pair of references:

using Logger = std::pair<std::ostream &, std::ostream &>;
Logger logger { output, error };

Instead of copying, which is not supported for streams, you can make pair of references to them

auto logger{::std::tie(output, error)};
Related