问题不在于如何从boost::asio::streambuf
. 相反,产生的错误是因为编译器选择的是非streambufwrite(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>&);
就编译器而言,第一个是更好的匹配,因为它是精确匹配,因此被选中。
这是一个完整的示例,演示了可编译的代码:
#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));
}