0

我需要将消息输出到控制台和日志文件。谷歌搜索后,我学习了“teebuf”概念,它基本上创建了一个从 basic_streambuf 继承的自定义类。这工作正常,但如何正确清理重定向的缓冲区。我的意思是如何为“tee”缓冲区实现 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”的不可访问基础

4

1 回答 1

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'错误消息的内容。

于 2012-10-10T08:33:25.310 回答