Consider a library function that takes a callback function (pointer) as argument. If a regular function pointer is used, the function can be used with regular C and C++ functions, but no class methods can be used for that:
typedef void(*CALLBACK_T)(int);
void testCallback(CALLBACK_T cb){
cb(5);
}
void intOut(int i){
std::cout << i << std::endl;
}
class Test{
public:
void intOut2(int i){
std::cout << "Test: " << i << std::endl;
}
};
void test(void){
testCallback(&intOut);
Test t;
testCallback(&t.intOut2); //won't work
}
I could use std::function
to encapsulate class members, but this would break C compatibility.
The only option I can think of is to create an additional context pointer to the callback handler:
typedef void(*CALLBACK2_T)(int, void*);
void testCallback2(CALLBACK2_T cb, void* context){
cb(5, context);
}
but this would require to keep track of the context information as well (the callback isn't directly invoked within the library function).
Do you have a better idea how a callback can be used with C functions and C++ class members at the same time?