如何将 boost::bind 对象存储为类成员?
我正在编写一个使用 boost::asio
的应用程序。 Asio 的 async_receive
(或 async_read
)总是使用为回调提供的 boost::bind
对象来显示:
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(),
chat_message::header_length),
boost::bind(&chat_session::handle_read_header,
shared_from_this(),
boost::asio::placeholders::error));
这非常好,但我想要不必在每次调用回调后重新创建绑定对象。相反,我想在类的构造函数中创建该对象,并将其交给 async_receive。
问题是,我不知道如何将该对象声明为类成员。我只知道auto,而且它显然不能作为班级成员工作。
class Whatever
{
public:
Whatever()
{
functor = boost::bind(&Whatever::Callback);
}
private:
void Callback()
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(),
chat_message::header_length),
functor);
}
?? functor; // How do I declare this?
...
};
注意:这很可能是过早的优化,但我仍然想知道如何在没有 auto 的情况下声明绑定对象。
I'm writing an application that uses boost::asio
. Asio's async_receive
(or async_read
) is invariably shown using a boost::bind
object given for callback:
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(),
chat_message::header_length),
boost::bind(&chat_session::handle_read_header,
shared_from_this(),
boost::asio::placeholders::error));
That's perfectly nice, but I'd like not to have to recreate the bind object after each call to the callback. Instead, I'd like to create the object, say, in the constructor of my class, and give it to async_receive.
The problem is, I don't know how to declare that object as a class member. All I know is auto, and it obviously won't work as a class member.
class Whatever
{
public:
Whatever()
{
functor = boost::bind(&Whatever::Callback);
}
private:
void Callback()
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(),
chat_message::header_length),
functor);
}
?? functor; // How do I declare this?
...
};
Note: This may very well be premature optimization, but I'd still like to know how to declare a bind object without auto.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
boost::function
:... 或类似的东西。
Use
boost::function
:... or something like that.
我猜您正在寻找增强函数。
只要签名正确,您就可以将绑定表达式的结果分配给 boost::function 对象。
I guess you are looking for boost function.
You can assign the result of your bind expression to a boost::function object as long as the signature is correct.
执行此操作的“标准”方法是使
functor
成为std::function
。如果您确实想存储实际的活页夹对象,请查看涉及活页夹的编译错误消息以找出确切的类型,并尝试使用它们来确定活页夹对象的实际类型。
The "standard" way of doing this is to make
functor
be astd::function
.If you really want to store the actual binder object, then look at compile error messages involving the binder to figure out the exact type, and try using those to determine the actual type of the binder object.
boost::bind 的返回类型是 boost::function< /a>.这是一个使用非常简单的函数的快速示例:
在您的情况下,该函数具有以下类型:
The return type of boost::bind is a boost::function. Here's a quick example using a very simple function:
In your case the function has this type: