Callback类模板的实际用途是什么?

时间:2016-02-18 08:42:53

标签: c++ templates callback

我试图理解回调的所有用法,但我在这里偶然发现了这段代码,我很难理解这个模板类的优点。在main中我创建了一个类FooBar的对象,然后我创建了一个CallBack类的对象,所以我可以在FooBar中调用该方法。我认为是无所事事的额外工作,因为它已经创建的对象(FooBar ob1),为什么不直接调用该函数?

 template <typename  T>
    class CallBack {
    public:
        public:
      typedef void (T::*methodcb)() const; //can you help me understand what the author did there?



  CallBack(): m_object(NULL), m_cb(NULL) {} 
  CallBack( T& object, methodcb cb) : m_object(&object), m_cb(cb)  {}

  void operator()(){ 
      if (m_object != NULL && m_cb != NULL) {
        (m_object->*m_cb)();
    }
  };

    private:
  T* m_object;
 methodcb m_cb;

};

class FooBar{

public:

void foo() const { std::cout << "Foo" << std::endl; } 
void bar() const { std::cout << "Bar" << std::endl; }

};

1 个答案:

答案 0 :(得分:1)

回调可以帮助我们在完成时将完成的内容去耦。如,

void do_sth(CallBack<FooBar> c) {
    // do something before...
    c();
    // do something after...
}

FooBar foobar;
if () 
    do_sth(CallBack<FooBar>(foobar, &FooBar::foo));
else
    do_sth(CallBack<FooBar>(foobar, &FooBar::bar));

或减少代码重复,

Object.getOwnPropertyDescriptor(obj, 'name');
> Object {value: "xyz", writable: true, enumerable: true, configurable: true}

回调通常用于Command pattern