コンソールファイルとログファイルの両方にメッセージを出力する必要があります。グーグルした後、基本的にbasic_streambufから継承されたカスタムクラスを作成する「teebuf」の概念を学びました。これは正常に機能しますが、リダイレクトされたバッファを適切にクリーンアップする方法です。「ティー」バッファにRAIIを実装する方法を意味するので、プログラムを終了する必要があるたびにそれを気にする必要はありません。
備考:現在、Boostライブラリを使用することは私にとってオプションではありません。
コードセグメント
int main() {
std::streambuf* cout_sbuf = std::cout.rdbuf();
std::ofstream fout(fileOutDebug);
teeoutbuf teeout(std::cout.rdbuf(), fout.rdbuf());
std::cout.rdbuf(&teeout);
// some code ...
if (failed) {
std::cout.rdbuf(cout_sbuf); // <-- i once comment this and it gives error
return -1;
}
// some more code ...
std::cout.rdbuf(cout_sbuf); // <-- i once comment this and it gives error
return 0;
}
コードセグメント(私の試用版の実装ですが、失敗します)
template < typename CharT, typename Traits = std::char_traits<CharT>
> class basic_tostream : std::basic_ostream<CharT, Traits>
{
public:
basic_tostream(std::basic_ostream<CharT, Traits> & o1,
std::basic_ostream<CharT, Traits> & o2)
: std::basic_ostream<CharT, Traits>(&tbuf),
tbuf(o1.rdbuf(), o2.rdbuf()) {}
void print(char* msg);
private:
basic_teebuf<CharT, Traits> tbuf; // internal buffer (tee-version)
};
typedef basic_tostream<char> tostream;
int main() {
std::ofstream fout(fileOutDebug);
tostream tee(std::cout, fout, verbose);
tee << "test 1\n"; // <-- compile error
tee.print("sometext"); // <-- comment above and it run fine, both file and console written
}
エラーメッセージ:「std::basic_ostream」は「basic_tostream」のアクセスできないベースです