Top/article/Dual-ostream
English | Japanese
English | Japanese

Menu

  • Top
  • Akihiko Yamaguchi 山口 明彦
  • Project プロジェクト
  • Text テキスト
  • Recent articles 最近の記事
  • Articles 記事一覧 (a to z)
  • Search 検索

Tags タグ †

  • [c++][bash][python][latex][php]
  • [linux][windows][mac][android]
  • [math][algorithm][idea][trick]
  • [liboctave][opencv][git][ros]
  • [setting][bug][general]
↑

Recent articles 最近の記事 †

2019-07-02
  • article/Display-Unix-Time
  • article/Synchronize-Linux-Time-to-Remote
2018-09-27
  • article/python-multimode-singleton
2018-09-02
  • article/rosinstall-git-default-remote
2017-07-28
  • article/SubMenu
2017-03-05
  • article/Import-a-different-version-of-OpenCV-in-Python
2015-08-17
  • article/DRC-finals-2015
2015-01-05
  • article/Upgrade-Android-to-Lollipop
2015-01-01
  • article/Kernel-panic-of-Linux-when-using-Xtion
  • article/Do-not-skip-freeing-data-when-using-tri-mesh-in-ODE
Access: 1/1858 - Admin
These search terms have been highlighted:[c++]

C++: Simultaneous output to double ostream

C++で2つの ostream に同時出力する

[c++]
2008-06-30

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();

のように使う.




Last-modified:2014-12-30 (Tue) 18:29:57 (3839d)
Site admin: Akihiko Yamaguchi.
Written by: Akihiko Yamaguchi.
System: PukiWiki 1.5.0. PHP 5.2.17. HTML conversion time: 0.007 sec.