有没有一种方便/巧妙的方法可以同时插入到多个输出流中?我知道我可以创建一个重载 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/