我有以下情况,(在代码中更好)
class Foo
{
private:
typedef boost::signal<void ()> Signal;
Signal signal;
public:
void Register_SignalFunction(const Signal::slot_type& slot);
void Unregister_SignalFunction(const Signal::slog_type& slot);
}
class OtherFoo
{
Foo foo;
public:
OtherFoo()
{
foo.Register_SignalFunction(&OnSignal) //I know I can't do this that is precisely my question.
}
void OnSignal(); //what to do when signal fires
} 所以问题是,我如何将一个“成员函数”指针传递给Register方法。还有,这样可以吗?我想要/需要的是某种代表注册系统,所以如果有人能给我指明正确的方向,我将不胜感激。提前谢谢。
发布于 2011-08-23 13:05:55
您通常会使用boost bind:
foo.Register_SignalFunction(boost::bind(&OtherFoo::OnSignal,this));
这是怎么回事?:-)
信号的connect方法需要一个functor。这是一个实现()运算符的对象。bind接受函数指针(指向自由函数或成员函数)并返回具有正确签名的函数器。
另请参阅此处:
Complete example using Boost::Signals for C++ Eventing
还有这里:
how boost::function and boost::bind work
要断开信号连接,请将connect的返回值存储到:
boost::signals::connection然后对其调用disconnect方法。
发布于 2011-08-23 12:17:07
通常,您将执行以下操作:
void Register_SignalFunction(const boost::function<void()> &slot) {
signal += slot;
}或者,作为内联函数:
template<typename T>
void Register_SignalFunction(T &slot) {
signal += slot;
}通过移除boost::function所具有的间接层,后者可能会稍微更有效一些--但前提是boost::signal不在内部使用boost::function (它很可能会这样做)。因此,请使用您喜欢的任何一个,真的。
发布于 2011-08-24 01:38:43
在尝试了很多次之后,我让它工作了,下面是代码:
GraphicsDeviceManager
{
private:
typedef boost::signal<void ()> DeviceLost;
DeviceLost deviceLost;
public:
Register_DeviceLostHandler(const boost::function<void ()> &handler)
{
deviceLost.connect(slot);
}
Unregister_DeviceLostHandler(const boost::function<void ()> &handler)
{
//deviceLost.disconnect(slot);
}
}
class GameBase
{
private:
GraphicsDeviceManager* graphics;
public:
GameBase()
{
graphics = new GraphicsDeviceManager();
graphics->Register_DeviceLostHandler(boost::bind(&GameBase::OnDeviceLost, this));
}
void OnDeviceLost()
{
//do some stuff
}
}这段代码可以正常工作,但有一个例外,如果我取消注释deviceLost.disconnect(处理程序)语句,我会收到如下编译错误: error C266 "boost::operator ==":4重载有类似的转换。
那么,为什么会发生这种情况呢?你知道有什么其他方法可以完成我正在尝试的事情吗?
https://stackoverflow.com/questions/7156135
复制相似问题