如何设置正确的回调来检索数据
how to setup a proper callback to retrieve data
我有以下情况,我有两个类。我通过回调函数将类1的实例传递给类2的实例。最终的目标是连接到某个东西(比如sql server)并检索一些数据集,可能每x分钟检索一次。我该如何修改下面的内容,以便在将类1的对象传递给类2的对象之后,我可以以某种方式让对象1完成所有的工作。从本质上讲,我需要连接到SQl并将数据放在类foo的work()函数中的实现。更重要的是,我如何在main()中将结果集中继回用户;
这有道理吗?正确吗?最终目标是锁定sql服务器,每5分钟获取一个数据集,并生成一些统计信息返回给用户,这是否应该修改?连接应该由foo类还是bar类处理
class foo{
public:
void work(int id, &result){}
};
class bar{
private:
foo* foo_
public:
void callback(foo* tempfoo){
foo_ = tempfoo;
}
void work();
};
int main(){
foo send;
bar receive;
receive.callback(&send);
//do a bunch of stuff with the receive object to get the result
bar.work(//some parameters that are needed to generate the result);
}
非常感谢各位。
想要调用回调的类应该获取一个函数指针,然后在适当的时候(当工作完成时)调用该指针。
关于如何准确地传递函数指针,有几个选项。您可以使用Lambda(如下面的示例代码所示),也可以使用std::bind和一个成员函数。
以下示例:
class foo(){
public:
foo()
~foo()
work(int id, &result){
//do work
//call callback with some params
callback(PARAMS);
}
void setCallback(std::function<void(PARAMETERS)> cb){
callback = cb;
}
private:
std::function<void(PARAMETERS)> callback = nullptr;
}
class bar(){
private:
foo* foo_
public:
bar()
~bar()
work();
}
int main(){
foo send;
bar receive;
receive.setCallback([](PARAMETERS){
//your callback code in lambda
//send and receive are not captured here
//if you wish to capture send and receive
//you should somehow maintain their existence in memory
//until the callback is called, otherwise you'll get bad access error
//due to those guys already destroyed
//to capture send and receive you should put them into [] of lambda declaration.
//Append & if you want to capture by reference.
});
receive.work(//some parameters that are needed to generate the result);
}
相关文章:
- 架构决策:返回std::future还是提供回调
- 正在为Xtensa simcall函数编写回调函数
- 如何在C++中使用非静态成员函数作为回调函数
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 用于在回调中调用解析器的设计模式
- 如何使用C++对象的成员函数作为 C 样式回调?
- Java从C++回调到C++回调
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 从不同的 cpp 调用回调函数会导致bad_function_call
- pcap_handler回调仅在使用 NPCAP v0.9991 时包含空数据包
- 不带轮询的 SDL2 事件回调
- C++存储带有可变参数的回调
- 如何使用 Node-addon-API 实现 node-nan 回调
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 访问类C++ C 样式回调
- 处理类内的回调时,必须调用对非静态成员函数的引用
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- 正在从回调函数检索数据
- 如何设置正确的回调来检索数据