如何设置正确的回调来检索数据

how to setup a proper callback to retrieve data

本文关键字:回调 检索 数据 何设置 设置      更新时间:2023-10-16

我有以下情况,我有两个类。我通过回调函数将类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);
}