方法作为回调

method as callback

本文关键字:回调 方法      更新时间:2023-10-16

我已经用接口实现了我的回调。

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;
   }
}