保存舊的流緩衝您更改cout
的流緩衝之前:
auto oldbuf = cout.rdbuf(); //save old streambuf
cout.rdbuf(s_outF.rdbuf()); //modify streambuf
cout << "Hello File"; //goes to the file!
cout.rdbuf(oldbuf); //restore old streambuf
cout << "Hello Stdout"; //goes to the stdout!
你可以寫一個restorer
自動做,因爲:
class restorer
{
std::ostream & dst;
std::ostream & src;
std::streambuf * oldbuf;
//disable copy
restorer(restorer const&);
restorer& operator=(restorer const&);
public:
restorer(std::ostream &dst,std::ostream &src): dst(dst),src(src)
{
oldbuf = dst.rdbuf(); //save
dst.rdbuf(src.rdbuf()); //modify
}
~restorer()
{
dst.rdbuf(oldbuf); //restore
}
};
現在用它的基礎上範圍作爲:
cout << "Hello Stdout"; //goes to the stdout!
if (condition)
{
restorer modify(cout, s_out);
cout << "Hello File"; //goes to the file!
}
cout << "Hello Stdout"; //goes to the stdout!
最後cout
將輸出到stdout
即使condition
是true
並執行if
塊。