Tutorial

1.1. Overview: Devices, streambuf_facade and stream_facade

Writing a new stream or stream buffer class using the Boost Iostreams library is easy: we simply write a class modeling the Device concept, then use that class as the template argument to streambuf_facade:

#include <boost/iostreams/stream_facade.hpp>
#include <boost/iostreams/streambuf_facade.hpp>

namespace io = boost::iostreams;

class my_device { /* */ };

typedef io::stream_facade<my_device>     my_stream;
typedef io::streambuf_facade<my_device>  my_streambuf;

Here io::stream_facade<my_device> is a derived class of std::basic_streambuf, and io::stream_facade<my_device> is a derived class of std::basic_istream, std::basic_ostream or std::basic_iostream depending on the mode of my_device, i.e., depending on which of the fundamental i/o operations read, write and seek it supports.

The template io::stream_facade is provided as a convenience. It's always possibly to avoid io::stream_facade<my_device> and simply use io::stream_facade together with one of the standard library stream templates. E.g.,

#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream_facade.hpp>

namespace io = boost::iostreams;

int main()
{
    io::stream_facade<file_sink> buf("log.txt");
    std::ostream out(&buf);
    // Write to out
}
typedef io::stream_facade<my_device>     my_stream;
typedef io::streambuf_facade<my_device>  my_streambuf;

Another way to define a new stream or stream buffer class using the Boost Iostreams library is to derive from filtering_stream or filtering_streambuf.

The next three items will demonstrate how to write Devices for accessing STL-compatible containers. The source code for the examples can be found in the header <libs/iostreams/example/container_device.hpp>