源自 `boost::asio::streambuf`

Deriving from `boost::asio::streambuf`

我正在尝试创建我的 class,它只是 public - 从 boost::asio::streambuf 派生并添加了一些方法:

class my_super_streambuf : public boost::asio::streambuf {
public:  
  void my_super_method();
};

但是当我简单地将boost::asio::streambuf替换为my_super_streambuf时出现了错误:

error C2039: 'const_iterator' : is not a member of 'my_super_streambuf'

D:\projects\my_super_streambuf\third-party\boost\boost/asio/impl/write.hpp(199) : 
see reference to class template instantiation
'boost::asio::detail::consuming_buffers<boost::asio::const_buffer,
ConstBufferSequence>' being compiled

如何正确地从 boost::asio::streambuf 推导出来?

您确定 "const_iterator" 是 "boost::asio::streambuf" 的 public 成员吗?

我试过这些代码,它有效:

class MyVector : public std::vector<int>{};
int main(int argc, const char * argv[]) {
    MyVector v;
    v.push_back(1);
    for (MyVector::const_iterator iter = v.begin(); iter != v.end(); iter++) {
        cout << *iter << endl;
    }
}

还有这些:

class MyBase {
    public:
        typedef int base_int;
};
class MyDerived : public MyBase {};

MyDerived::base_int P = 5;
MyBase::base_int Q = 5;

问题不在于如何从 boost::asio::streambuf. Instead, the resulting error is because the compiler is selecting the non-streambuf write(SyncWriteStream&, const ConstBufferSequence&) overload instead of write(SyncWriteStream&, basic_streambuf<Allocator>&) 派生。要解决这个问题,可以在调用 write():

时显式地将派生自 boost::asio::streambuf 的对象转换为 boost::asio::streambuf 的引用
class derived_streambuf
  : public boost::asio::streambuf
{};

// ...

derived_streambuf streambuf;
boost::asio::write(socket, static_cast<boost::asio::streambuf&>(streambuf));

要理解这个问题,请考虑相关重载函数的声明:

// ConstBufferSequence
template<
    typename SyncWriteStream,
    typename ConstBufferSequence>
std::size_t write(
    SyncWriteStream&,
    const ConstBufferSequence&);

// Streambuf
template<
    typename SyncWriteStream,
    typename Allocator>
std::size_t write(
    SyncWriteStream&,
    basic_streambuf<Allocator>&);

如果将 derived_streambuf 作为第二个参数提供,函数的实例化将导致:

// ConstBufferSequence
std::size_t write(..., derived_streambuf&);

// Streambuf
std::size_t write(..., basic_streambuf<char>&);

对于编译器而言,第一个是更好的匹配,因为它是精确匹配,因此选择它。


这里是一个完整的示例demonstrating编译代码:

#include <boost/asio.hpp>

// Derive from boost::asio::streambuf.
class derived_streambuf
  : public boost::asio::streambuf
{};

// Helper function to force type.
template <typename Allocator>
boost::asio::basic_streambuf<Allocator>&
as_streambuf(boost::asio::basic_streambuf<Allocator>& streambuf)
{
  return streambuf;
}

int main()
{
  boost::asio::io_service io_service;
  boost::asio::ip::tcp::socket socket(io_service);
  derived_streambuf streambuf;
  boost::asio::write(socket, static_cast<boost::asio::streambuf&>(streambuf));
  boost::asio::write(socket, as_streambuf(streambuf));
}