How do I implement a callback in C++?

前端 未结 6 2229
野性不改
野性不改 2020-12-05 19:52

I want to implement a class in c++ that has a callback.

So I think I need a method that has 2 arguments:

  • the target object. (let\'s say *myObj)
  • <
6条回答
  •  我在风中等你
    2020-12-05 20:19

    The best solution, use boost::function with boost::bind, or if your compiler supports tr1/c++0x use std::tr1::function and std::tr1::bind.

    So it becomes as simple as:

    boost::function callback;
    Target myTarget;
    callback=boost::bind(&Target::doSomething,&myTarget);
    
    callback(); // calls the function
    

    And your set callback becomes:

    class MyClassWithCallback{
    public:
      void setCallback(boost::function const &cb)
      {
         callback_ = cb;
      }
      void call_it() { callback_(); }
    private:
      boost::function callback_;
    };
    

    Otherwise you need to implement some abstract class

    struct callback { 
     virtual void call() = 0;
     virtual ~callback() {}
    };
    
    struct TargetCallback {
     virtual void call() { ((*self).*member)()); }
     void (Target::*member)();
     Target *self;
     TargetCallback(void (Target::*m)(),Target *p) : 
           member(m),
           self(p)
     {}
    };
    

    And then use:

    myCaller.setCallback(new TargetCallback(&Target::doSomething,&myTarget));
    

    When your class get modified into:

    class MyClassWithCallback{
    public:
      void setCallback(callback *cb)
      {
         callback_.reset(cb);
      }
      void call_it() { callback_->call(); }
    private:
      std::auto_ptr callback_;
    };
    

    And of course if the function you want to call does not change you may just implement some interface, i.e. derive Target from some abstract class with this call.

提交回复
热议问题