gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:14:38 24 4
gpt4 key购买 nike

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

};

最佳答案

回调可以帮助我们将完成的什么何时完成分离。比如,

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中.

关于c++ - Callback 类模板的实际用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35476553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com