0

std::cout.rdbuf()很容易使用。但我希望将字符串打印到控制台并将其写入文件。

所以我想的是把两个流缓冲区封装到一个派生类中std::streambuf,并将其传递给rdbuf(). 那可能吗?

我应该如何做到这一点?

4

1 回答 1

1

我认为一个更好的方法是将两个流封装到一个实际的流类中,从std::basic_ostream<...>.

首先是:

template<class charT, class traits = std::char_traits<charT>>
class basic_binary_stream : public std::basic_osteam<charT>
{
    typedef std::basic_ostream<charT> stream_type;
    typedef std::char_traits<charT>   traits_type;
    /* ... */
public:
    binary_stream(stream_type& o1, stream_type& o2)
        : s1(o1), s2(o2)
    { }

    binary_stream& operator<<(int n)
    {
        s1 << n;
        s2 << n;
        return *this;
    }

    /* ... */
private:
    stream_type& s1, &s2;
};

using binary_stream = basic_binary_stream<char>;
于 2014-01-13T00:45:18.617 回答