方法作为回调
method as callback
我已经用接口实现了我的回调。
struct ICallback
{
virtual bool operator()() const = 0;
};
和用于添加回调的函数
void addCallback(const ICallback* callback) { .... }
并使用,回调在某个类中
class BusImplemantation{
public:
struct Foo : ICallback
{
virtual bool operator()() const { return true;}
}foo;
void OtherMethod();
int OtherMember;
};
但是因为回调是类(不是函数/方法),所以我不能回调访问 OtherMethod 和 OtherMember。如果回调不是类,而只是方法,那么它是不可能的。(内部类与方法)
我无法将其他方法和其他成员作为参数传递给回调。
有没有更好的解决方案? 也许有模板?
使用 std::function
:
void addCallback(const std::function<bool()>) { .... }
class BusImplemantation{
public:
bool Callback() { return true; }
void OtherMethod();
int OtherMember;
};
BusImplemantation obj;
addCallback(std::bind(&BusImplemantation::Callback, obj));
查看boost::bind 以获取有关如何实现这一点的一系列替代方案。
你能做这样的事情吗:
typedef std::function<bool()> CallbackFunc;
void addCallback(const CallbackFunc callback) { .... }
class BusImplemantation{
public:
struct Foo
{
Foo(member) : OtherMember(member) { }
bool operator()() const { return true; }
void OtherMethod();
int OtherMember;
}foo;
};
不要使回调成为接口,而是使用 std::function 使其成为函数对象(Functor),并且函子所需的任何额外数据或方法都可以成为函子类的一部分。
使用回调对象而不是自由函数的全部意义在于您可以将任意状态与它们相关联:
class BusImplemantation{
public:
struct Foo : ICallback
{
explicit Foo(BusImplementation &p) : parent(p) {}
virtual bool operator()() const;
private:
BusImplementation &parent;
} foo;
BusImplementation() : foo(*this)
{
addCallback(&foo)
}
void OtherMethod();
int OtherMember;
};
bool BusImplementation::Foo::operator() () const
{
if (parent.OtherMember == 0) {
parent.OtherMethod();
return false;
}
return true;
}
我认为您的ICallback
接口必须具有指向具有基本接口的受控类的指针,假设它BusImplemantation
并在内部回调使用此指针。
struct ICallback
{
virtual bool operator()() const = 0;
void setControlObject(BusImplemantation* o)
{
obj = o;
}
BusImplemantation* obj;
};
class BusImplemantation
{
public:
void addCallback(const ICallback* callback)
{
callback->setControlObject(this);
}
void OtherMethod();
int OtherMember;
};
并使用:
class SomeCb : ICallback
{
bool operator()
{
obj->OtherMethod();
return true;
}
}
相关文章:
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- C++ - 如何在不静态的情况下将回调绑定到类方法?
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- 回调方法显示错误,类型为"void(*)"的值不能用于初始化类型的实体
- 全局挂钩 DLL 仅在 C# 主窗口处于活动状态/前台时调用 C# 回调方法
- 如何从回调方法访问自定义类成员
- 异步I/O回调方法并发
- 苹果运行循环的回调方法
- C++如何通过回调方法访问成员变量
- VS2013 wndProg 回调方法
- 回调方法无法访问成员变量或实例
- 定义glDebugMessageCallbackARB回调方法
- pcap_loop中的回调方法
- ROS:subscribe函数无法识别我的回调方法
- 在构造函数中绑定到类中的回调方法
- GLUT回调方法问题
- DirectShow从内存中读取一个回调方法
- c++装饰器模式,带有模板的静态多态性和注册回调方法
- 如何为IAsyncOperation指定一个回调方法
- 在c代码中注册一个c++回调方法