1

我正在尝试创建我的类,它只是公共派生的,boost::asio::streambuf并添加了一些方法:

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

但是当我简单地替换boost::asio::streambufmy_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

4

2 回答 2

3

问题不在于如何从boost::asio::streambuf. 相反,产生的错误是因为编译器选择的是非streambufwrite(SyncWriteStream&, const ConstBufferSequence&)重载而不是write(SyncWriteStream&, basic_streambuf<Allocator>&). 为了解决这个问题,可以在调用时将派生自的对象显式boost::asio::streambuf转换为的引用:boost::asio::streambufwrite()

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>&);

就编译器而言,第一个是更好的匹配,因为它是精确匹配,因此被选中。


这是一个完整的示例,演示了可编译的代码:

#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));
}
于 2015-07-16T00:56:52.873 回答
0

你确定有一个“const_iterator”作为“boost::asio::streambuf”的公共成员吗?

我尝试了这些代码,它可以工作:

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;
于 2015-07-15T07:56:49.783 回答