2012-10-10 76 views
0

我需要將消息輸出到控制檯和日誌文件。 谷歌搜索後,我學到了「teebuf」概念,它基本上創建了一個從basic_streambuf繼承的自定義類。這工作正常,但如何正確地清理重定向的緩衝區。我的意思是如何實現RAII的「三通」緩衝區,所以當我需要退出程序時,我不需要打擾它。C++正確清理重定向緩衝區用於tee ostream

備註:目前使用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'

回答

0

您應該使用:

template < typename CharT, typename Traits = std::char_traits<CharT> > 
class basic_tostream : public std::basic_ostream<CharT, Traits> 

代替:

template < typename CharT, typename Traits = std::char_traits<CharT> > 
class basic_tostream : std::basic_ostream<CharT, Traits> 

主要區別是public。這就是'std::basic_ostream' is an inaccessible base of 'basic_tostream'錯誤信息。

+0

謝謝。有沒有其他建議來提高我的課程? –

+0

我對basic_teebuf不熟悉,但basic_tostream的簡單性表明它很優雅。 – CrazyCasta