我认为我的问题在这里很常见,但我只是不太明白我在这里做错了什么。
我正在做一些 boost::asio 的东西并尝试编写一个模板化的异步读取函数。
这是一个函数。
template <typename Handler>
void AsyncRead(std::vector<boost::uint8_t>& _inMsg, Handler _handler)
{
#if debug
std::cout<< "IConnection::AsyncRead" << std::endl;
#endif
using namespace protocols;
typedef boost::tuple<Handler> tHandler;
typedef boost::function< void(const boost::system::error_code &, std::vector<boost::uint8_t> &, tHandler ) > HeaderReaderFunc;
//void (AConnection::*f)(const boost::system::error_code&, std::vector<boost::uint8_t>&, boost::tuple<Handler>) = &AConnection::HandleReadHeader<Handler>;
tHandler t(boost::make_tuple(_handler));
HeaderReaderFunc x(boost::bind(&AConnection::HandleReadHeader<Handler>, this, boost::asio::placeholders::error, boost::ref(_inMsg), t));
inboundHeader.resize(sizeof(SocketIO::MsgData));
boost::asio::async_read(socket, boost::asio::buffer(inboundHeader), x);
}
在这个函数的最后一个语句中事情开始变糟了。
boost::asio::async_read(socket, boost::asio::buffer(inboundHeader), x);
当我尝试将变量“x”作为参数传递给 async_read 函数时。
这些错误在长度和缺乏可解读的含义方面都是传奇的。
只是错误输出的一个小例子:
boost_1_38_0/boost/asio/detail/bind_handler.hpp: In member function ‘void boost::asio::detail::binder2<Handler, Arg1, Arg2>::operator()() [with Handler = boost::function<void ()(const boost::system::error_code&, std::vector<unsigned char, std::allocator<unsigned char> >&, boost::tuples::tuple<boost::function<void ()(const boost::system::error_code&)>, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type>)>, Arg1 = boost::system::error_code, Arg2 = unsigned int]’:
如果我在这里不使用 boost 函数,而是使用注释掉的行,它是对成员函数的引用,事情似乎可以工作,但我无法弄清楚为什么会这样。
AConnection::HandleReadHeader 函数模板的函数签名是:
template <typename Handler>
void HandleReadHeader(const boost::system::error_code& _e,
std::vector<boost::uint8_t> & _inMsg,
boost::tuple<Handler> _handler)
处理程序的类型:
boost::function<void (const boost::system::error_code & ) >
函数 AsyncRead 和 HandleReadHeader 是我自己的类 AConnection 的成员(可能不重要)。
要么我遗漏了有关创建签名包含 boost::tuple 的 boost::function 对象的语法,要么我的变量 'x 不匹配 boost::asio::async_read 函数的第三个参数类型'。
任何帮助,将不胜感激。谢谢你。
编辑:
这是可以工作的代码,但使用成员函数引用而不是 boost::functon。
template <typename Handler>
void AsyncRead(std::vector<boost::uint8_t>& _inMsg, Handler _handler)
{
#if debug
std::cout<< "Connection::AsyncRead" << std::endl;
#endif
using namespace protocols;
// Issue a read operation to read exactly the number of bytes in a header.
void (Connection::*f)(
const boost::system::error_code&,
std::vector<boost::uint8_t>&, boost::tuple<Handler>)
= &Connection::HandleReadHeader<Handler>;
inboundHeader.resize(sizeof(simple::message_header));
boost::asio::async_read(socket, boost::asio::buffer(inboundHeader),
boost::bind(f,
this, boost::asio::placeholders::error, boost::ref(_inMsg),
boost::make_tuple(_handler)));
}