c++ - 如何封装两个流缓冲区

标签 c++ stream std iostream ofstream

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

所以我想到的是把两个stream buffer封装成一个std::streambuf的派生类,然后传给rdbuf()。这可能吗?

我应该如何实现?

最佳答案

我认为更好的方法是将两个流封装到派生自 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>;

关于c++ - 如何封装两个流缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18706563/

相关文章:

c++ - 如何在 C++ 中使用套接字?

node.js - 使用流时 knex.js 上的内存问题

c++ - MSVC 2010 中的 isnan() 在哪里?

c++ - Boost Beast 异步服务器因断言失败而失败:(id_!= T::id) 在多个 aync 调用中

c++ - 运算符优先级.. () 和++

c++ - 检测未插入的捕获设备 (OpenCV)

c++ - Python:类 C++ 流输入

c# - .NET 流,在对象之间传递流,最佳实践 (C#)

C++。 std::condition_variable 和多个等待线程

c++ - std::size 和 std::empty 的特化与模板不匹配