gpt4 book ai didi

c++ - 来自 `boost::asio::streambuf`

转载 作者:行者123 更新时间:2023-11-30 02:37:50 29 4
gpt4 key购买 nike

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

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 派生?

最佳答案

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

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

关于c++ - 来自 `boost::asio::streambuf`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31423582/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com