我用接口实现了我的回调。
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的范围内。如果回调不是类,而是方法而不是可能的。(内部类与方法)
I不能将OtherMethod和OtherMember作为参数传递给回调。
有什么更好的解决办法吗?也许用模板?
发布于 2012-09-21 14:19:29
使用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));发布于 2012-09-21 14:04:19
关于如何实现这一点,请查看助推::绑定中的一些替代方案。
发布于 2012-09-21 14:09:58
你能这样做吗?
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使其成为函数对象(函子),而函子需要的任何额外数据或方法都可以是函子类的一部分。
https://stackoverflow.com/questions/12532030
复制相似问题