Henrik Viebrock Henrik Viebrock - 5 months ago 43
C++ Question

c++ - Pointer to "unknown" class

I wrote a special class which checks some states of some external stuff and if something changes I would like to call a callback function.
These function should be not only a global function instead of a function of a special class.
To show what I mean here is some code:

void myClass::addCallbackFunction(unsigned int key, TheSpecialClass* obj, void (TheSpecialClass::*func)(unsigned int, bool)) {
if(!obj) {
callbackFunction cbf;
cbf.object = obj;
cbf.func = func;

if(!(callbackFunctions.find(key) == callbackFunctions.end())) {
//Key allready exists.
} else {
//Key does not exists at the moment. Just create it.
vector<callbackFunction> v;
callbackFunctions.insert({key, v});

void MyClass::callCallbackFunction(unsigned int key, bool newValue) {
vector<callbackFunction> cbfs;
if(!(callbackFunctions.find(key) == callbackFunctions.end())) {
cbfs = callbackFunctions[key];

//calling every function which should be called on a state change.
for(vector<callbackFunction>::iterator it = cbfs.begin(); it != cbfs.end(); ++it) {
((it->object)->*(it->func))(key, newValue);

//to show the struct and the used map
struct callbackFunction {
TheSpecialClass* object;
void (TheSpecialClass::*func)(unsigned int, bool) ;
map<unsigned int, vector<callbackFunction> > callbackFunctions;

Now I want to make 'TheSpecialClass' to some kind of Pointer to a class which can variate. I found void-Pointer but then I have to know which class I passed. I thought there is something like the function pointer out there which I did not found yet.

Do someone know a solution?

Answer Source

I used boost::signal2 to match my usecase. A tutorial for boost::signal2 is found here.

The signals whould only call functions. Not functions on a special object. There is a workaround by using boost::bind() like:

    boost::bind(boost::mem_fn(&SpecialClass::memberFunctionOfTheClass), PointerToTheObjectOfSepcialClass, _1)

The _1 is a placeholder which creates a function (reference) which requires one argument. You can add some more placeholders to use more arguments.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download