gpt4 book ai didi

c++ - 处理嵌套回调

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

我遇到了一个需要处理嵌套回调的情况。请参阅 Thing::process 函数。第二个 g_thing.onAfterWalk() 回调将永远不会被调用,因为父回调会在执行完毕后立即销毁它。

Thing g_thing;

void Thing::walk(int32_t x, int32_t y) {
if (SYSTIME() > m_walkEndTime) {
// Still walking
return;
}

auto obj = g_thing.localObject();
auto walkDuration = obj->getWalkDurationTo(x, y);
[..]
m_walkEndTime = SYSTIME() + walkDuration;

[..]

// Walk finished. Run callback
if (m_afterWalk) {
m_afterWalk();
m_afterWalk = nullptr;
}
}

void Thing::onAfterWalk(std::function<void(void)>& callback) {
m_afterWalk = callback;
}

void Thing::process() {
[..]
// Store a callback and walk
g_thing.onAfterWalk([]() {
// Store another callback
// After walking to 4321, 4321 do something else.
// My actual problem... Callback within callback
g_thing.onAfterWalk([]() {
std::cout << "Walking finished.\n";
});

// After walking to 1234, 1234 walk to 4321, 4321
g_thing.walk(4321, 4321);
});
g_thing.walk(1234, 1234);
}

如何处理这种嵌套回调?

我是否应该创建一个带有回调队列的 std::stack?什么是最好的方法?

最佳答案

对我有用(有一些调整:const 参数到 onAfterWalk,以及 std::cout.flush() 在结尾)。您确定您不只是丢失标准输出中的输出吗?

#include <iostream>
#include <functional>

class Thing;
extern Thing g_thing;

class Thing
{
std::function<void(void)> m_afterWalk;
public:
void walk()
{
if(m_afterWalk)
{
m_afterWalk();
m_afterWalk = nullptr;
}
}

void onAfterWalk(const std::function<void(void)>& callback)
{
m_afterWalk = callback;
}

void process()
{
// Store a callback and walk
g_thing.onAfterWalk([]() {
// Store another callback
g_thing.onAfterWalk([]() {
std::cout << "Walking finished.\n";
});
g_thing.walk();
});
g_thing.walk();
}
};

Thing g_thing;

int main(int argc, char *argv[])
{
g_thing.process();
std::cout.flush();
}

产量

$ g++ -pedantic -Wall -Werror test.cpp
$ ./a.out
Walking finished.

关于c++ - 处理嵌套回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47493620/

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