用于tee ostream的C ++正确清理重定向缓冲区

时间:2012-10-10 08:28:23

标签: c++ ostream

我需要将消息输出到控制台和日志文件。 谷歌搜索后,我学会了“teebuf”概念,它基本上创建了一个继承自basic_streambuf的自定义类。这工作正常,但如何正确清理重定向缓冲区。我的意思是如何为“tee”缓冲区实现RAII,所以每次我需要退出程序时都不需要打扰它。

备注:目前使用升级库不适合我。

代码段

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'无法访问的基础

1 个答案:

答案 0 :(得分: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'错误消息的内容。