【问题标题】:How to encapsulate two stream buffers如何封装两个流缓冲区
【发布时间】:2013-09-13 10:24:39
【问题描述】:

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

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

我应该如何做到这一点?

【问题讨论】:

标签: c++ stream std iostream ofstream


【解决方案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>;

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多