尝试从 boost::iostreams 访问源设备

Trying to access source device from boost::iostreams

我编写了一个自定义源设备来计算到目前为止读取的字节数:

class socket_stream_source : public boost::iostreams::source
{
public:

    int readSoFar=0;

    socket_stream_source(socket_ptr sock) : _sock(sock)
    {

    }

    std::streamsize read(char* s, std::streamsize n)
    {
        int readCount = _sock->read_some(boost::asio::buffer(s, n));
        readSoFar += readCount;
        return readCount;
    }

private:
    socket_ptr _sock;

};

我是这样使用的:

boost::iostreams::stream<socket_stream_source> in(sock);

如何访问我的 readSoFar 变量?

或者是否有另一种方法来计算到目前为止从 istream 读取的字节数?

只需使用boost::iostreams::stream提供的设备访问操作符,即

T& operator*();
T* operator->();

在你的代码中这就足够了:

in->readSoFar;