How to set up the correct callback to retrieve data

I have the following situation: I have two classes. I am passing an instance of class 1 to an instance of class two via a callback function. Ultimately the goal is to connect to something (like sql server) and get some datasets, maybe every x minutes. How do I modify the following so that after passing class 1 object to class 2 object, I can somehow get object 1 to do all the work. Basically, I need an implementation of connecting to SQl and getting data in the work () function of the foo class. and more importantly, how can I pass the result set back to the user in main ();

Does this make sense at all? Right? The end goal is to latch to the sql server and grab a dataset every 5 minutes and generate some statistics that will be returned to the user, if this is changed at all? If the connection should be handled by the foo class or the bar class

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

      

Thanks a lot guys.

+3


source to share


1 answer


The class that wants to invoke the callback must take a pointer to the function and then call the corresponding pointer (when the work is done).

There are several options for how to accurately pass a pointer to a function. You can use Lambda (like in the code example below), or you can use std :: bind with a member function.



See example below:

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

      

+2


source







All Articles