c++ - 指向 "unknown" class 的指针

c++ - Pointer to "unknown" class

我写了一个特殊的 class 来检查一些外部东西的一些状态,如果有什么变化我想调用一个回调函数。 这些函数应该不仅仅是一个全局函数而不是一个特殊的函数class。 为了说明我的意思,这里有一些代码:

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

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

void MyClass::callCallbackFunction(unsigned int key, bool newValue) {
    vector<callbackFunction> cbfs;
    //hasKey..
    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;

现在我想使 'TheSpecialClass' 指向某种可以变化的 class 的指针。我找到了 void-Pointer 但我必须知道我通过了哪个 class 。我以为那里有类似函数指针的东西,但我还没有找到。

有人知道解决方案吗?

我使用 boost::signal2 来匹配我的用例。 A tutorial for boost::signal2 is found here.

只能调用函数的信号。不适用于特殊对象。使用 boost::bind() 有一个解决方法,例如:

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

_1 是一个占位符,它创建一个需要一个参数的函数(引用)。您可以添加更多占位符以使用更多参数。