c++ - 插入多个输出流?

标签 c++

有没有一种方便/巧妙的方法可以同时插入到多个输出流中?我知道我可以创建一个重载 operator<< 的类转发插入内容,但是有没有更巧妙的方法可以做到这一点?谢谢!

最佳答案

我不认为它有简写形式,但假设您可以使用 C++11,那么定义一个模板类来执行您想要的操作会相对简单:

// 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...);
}

这让您可以即时决定输出到哪些:

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

关于c++ - 插入多个输出流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34214331/

相关文章:

c++ - 如何只在 Debug模式下编译一段源代码?

c++ - 是否有 C++ 位域的可移植替代品

c++ - 是否可以将 QTreeWidgetItem 的文本部分设为斜体?

c++ - C++-从 'node*&'类型的表达式对 'node'类型的引用的无效初始化

javascript - MongoDB 事件.js :85

c++ - 程序集中发生访问冲突写入位置

c++ - 返回临时的 const 引用

c++ - 序列化 : CArchive a CImage

c++ - 使用单独的 .h 和 .cpp 文件 boost 序列化

c++ - 如何按索引分配对象数组? (C++)