【问题标题】:What is the practical use of Callback class template?Callback类模板的实际用途是什么?
【发布时间】:2016-02-18 08:42:53
【问题描述】:

我试图理解回调的所有用法,但我在这里偶然发现了这段代码,我很难理解这个模板类的优点。在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; }

};

【问题讨论】:

  • 回调允许更改要调用的对象和/或方法。事实上,在一个简单的例子中来展示它是如何工作的,这个例子可以简单地重写为不使用回调。

标签: c++ templates callback


【解决方案1】:

回调可以帮助我们将 what 完成与 when 完成分离。比如,

std::vector<CallBack<FooBar>> commands;

// initialize the commands
// in charge of sepecifying WHAT will be invoked
FooBar foobar;
commands.emplace_back(foobar, &FooBar::foo);
commands.emplace_back(foobar, &FooBar::bar);

// ... ...

// no need to know the details about functions
// in charge of controlling WHEN will be invoked
for (auto command : commands) {
    command();
}

或减少代码重复,

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

回调通常用于Command pattern

【讨论】:

  • 嗯,这个例子是高级别的。你有更简单的吗?
  • 非常感谢,我会分解并尝试处理它。
  • @DraganItmSmoljan 希望对您有所帮助。
猜你喜欢
  • 2011-04-02
  • 2019-05-17
  • 2015-04-22
  • 2021-07-22
  • 1970-01-01
  • 2011-09-20
  • 2015-06-07
  • 1970-01-01
相关资源
最近更新 更多