C++で2つの ostream に同時出力する
C++で std::cout と std::ofstream のインスタンスに同じ内容を出力するとき,ほぼ同じコードを2回書かないとダメだ.
ofstream os ("tmp.dat"); dout(cout, os) << "x= " << x << endl;
こんな感じで,一文で書けるようにしたい.
で,上の例にあるような dout クラスを作ってみた:
class dout //! "double out" class. use this object to output the same value to two stream { private: std::ostream &os1, &os2; public: explicit dout (std::ostream &_os1, std::ostream &_os2) : os1(_os1), os2(_os2) {}; template <typename T> dout& operator<< (const T &rhs) { os1 << rhs; os2 << rhs; return *this; }; dout& operator<< (std::ostream& (*__pf)(std::ostream&)) { __pf(os1); __pf(os2); return *this; }; /*!< Interface for manipulators, such as \c std::endl and \c std::setw For more information, see ostream header */ };
ふたつ目の operator<< は, endl とか setw を使えるようにするためだ.
具体的には,
int x(10); ofstream os ("tmp.dat"); dout(cout, os) << "ureeee!!!" << endl; dout(cout, os) << "x= " << x << endl; dout(cout, os) << setw(5) << 3 << setw(5) << 19.0 << endl << "hogehoge" << endl; os.close();
のように使う.