mepcotterell
mepcotterell

Reputation: 2710

Insert into Multiple Output Streams?

Is there a convenient/slick way to insert into multiple output streams at the same time? I know I can create a class that overloads operator<< to forward the insertions, but is there any slicker way to go about doing this? Thanks!

Upvotes: 0

Views: 77

Answers (1)

Joe F
Joe F

Reputation: 652

I don't think there's a shorthand for it, but assuming you can use C++11 it is relatively straightforward to define a template class that does what you want:

// Recursive case.
template <typename T, typename ... TS>
class Output {
 public:
  Output(T& first, TS& ... rest)
      : first_(first), rest_(rest...) {}

  template <typename X>
  Output<T, TS...>& operator<<(X&& x) {
    // Output to each stream in the order that they were specified.
    first_ << x;
    rest_ << x;
    return *this;
  }
 private:
  T& first_;
  Output<TS...> rest_;
};

// Base case.
template <typename T>
class Output<T> {
 public:
  Output(T& output)
      : output_(output) {}

  template <typename X>
  Output<T>& operator<<(X&& x) {
    output_ << x;
    return *this;
  }
 private:
  T& output_;
};

// Function so that types can be inferred.
template <typename ... TS>
Output<TS...> tee(TS&&... outputs) {
  return Output<TS...>(outputs...);
}

This lets you decide on the fly which ones to output to:

tee(std::cout, std::cerr, std::ofstream("my_file.txt"))
    << "Hello, World!\n";

Upvotes: 1

Related Questions