我按照这个提升示例构建了一个自定义处理程序分配器:http://www.boost.org/doc/libs/1_56_0/doc/html/boost_asio/example/cpp03/allocation/server.cpp
在自定义处理程序上调用io_service.post()会给出错误:
No matching function for call to object of type 'custom_alloc_handler<void (*)()>
以下是一些示例代码:
#include <iostream>
#include "boost/asio.hpp"
#include "boost/bind.hpp"
#include "boost/asio/handler_alloc_hook.hpp"
#include <boost/aligned_storage.hpp>
class handler_allocator
: private boost::noncopyable
{
public:
handler_allocator()
: in_use_(false)
{
}
void* allocate(std::size_t size)
{
if (!in_use_ && size < storage_.size)
{
in_use_ = true;
return storage_.address();
}
else
{
return ::operator new(size);
}
}
void deallocate(void* pointer)
{
if (pointer == storage_.address())
{
in_use_ = false;
}
else
{
::operator delete(pointer);
}
}
private:
boost::aligned_storage<1024> storage_;
bool in_use_;
};
template <typename Handler>
class custom_alloc_handler
{
public:
custom_alloc_handler(handler_allocator& a, Handler h)
: allocator_(a),
handler_(h)
{
}
template <typename Arg1>
void operator()(Arg1 arg1)
{
handler_(arg1);
}
template <typename Arg1, typename Arg2>
void operator()(Arg1 arg1, Arg2 arg2)
{
handler_(arg1, arg2);
}
friend void* asio_handler_allocate(std::size_t size,
custom_alloc_handler<Handler>* this_handler)
{
return this_handler->allocator_.allocate(size);
}
friend void asio_handler_deallocate(void* pointer, std::size_t /*size*/,
custom_alloc_handler<Handler>* this_handler)
{
this_handler->allocator_.deallocate(pointer);
}
private:
handler_allocator& allocator_;
Handler handler_;
};
template <typename Handler>
inline custom_alloc_handler<Handler> make_custom_alloc_handler(
handler_allocator& a, Handler h)
{
return custom_alloc_handler<Handler>(a, h);
}
void handler()
{
std::cout << "handler called" << std::endl;
}
int main(int argc, const char * argv[])
{
boost::asio::io_service ioService;
handler_allocator allocator;
ioService.post(
make_custom_alloc_handler(allocator, &handler)
);
return 0;
}
问题似乎是由于BOOST_ASIO_COMPLETION_HANDLER_CHECK
失败。
我找不到办法让它发挥作用。
答案 0 :(得分:2)
原因是你必须在custom_alloc_handler
中拥有正确的模板功能!
void operator()()
{
handler_();
}