是否有方便/光滑的方式同时插入多个输出流?我知道我可以创建一个重载operator<<
来转发插入的类,但有没有更明智的方法来做这个?谢谢!
答案 0 :(得分:1)
我不认为它有一个简写,但假设您可以使用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";