Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid replicating callback functions (C++)

I am using an API which only accepts void callback functions:

void (* CALLBACKFUNC) (void);

I want to call the callback function with parameters, instead of writing multiple callback functions with the same functionality for different input parameters. Let's say I need a callback function like

void myFunc (int a);

UPDATE: more information: calling the callback function, based on the events should be like:

event1 -> calling myFunc(1);
event2 -> calling myFunc(2);
...

The number of events is limited and a MAX is predefiend (if it helps), but I do not want to replicate the functionality (actually, in the real case, there are multiple input values, and replicating the function call for the different combinations is not an easy job)

P.S: I can use C++11 as well. Any suggestions?.

like image 343
towi_parallelism Avatar asked Feb 11 '23 07:02

towi_parallelism


1 Answers

What about this solution? You don't need to define manually new function to set different states.

#include <iostream>

void setState(int s) {

    std::cout << "Set state to " << s << std::endl;

}

template <int n>
void myWrapper() {
    setState(n);
}


void myLogic(void(*CALLBACK)(void)) {

    CALLBACK();
}


int main(int argc, char* argv[]) {


    myLogic(myWrapper<50>);
    myLogic(myWrapper<100>);

}
like image 109
Krab Avatar answered Feb 13 '23 04:02

Krab