I have lots of instances of class X
and each of them contain another class CB
(sometimes more than one CB
). The CB
class has a function pointer in it that will be called after some event (click, timer, etc).
It would be so useful if I could just pass an instances member function to the local CB
class instance (pass the say()
function in this case) so that once CB
triggers the function, it will modify things in its own instance only.
Example sample code:
#include <iostream>
class CB {
void (*function)(void);
void init(void (*function)(void)) {
this->function = function;
}
};
class X {
private:
CB cb;
public:
void init() {
cb.init( &(this->say) ); //<- Here's the problem
}
void say() {
std::cout << "Hello World!" << std::endl;
}
};
int main() {
X x;
x.init();
}
So my above example fails due to line 17 with the error:
no known conversion for argument 1 from ‘void (X::*)()’ to ‘void (*)()’
Is it possible to somehow pass an instances local say()
function to the instances CB
? The CB
function can't be modified and unfortunately will be used by other classes of a different type.
I've read in other threads that this is most likely impossible unless the say()
function is static
or exists outside the class (which means it won't have access to an instances variables).
Is it possible to get this to work the way I have it? If not what would be the most common solutions (this seems like an issue a lot of people would run into)?