【问题标题】:c++ - Pointer to "unknown" classc++ - 指向“未知”类的指针
【发布时间】:2017-07-07 19:11:13
【问题描述】:

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

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”设为某种指向可以变化的类的指针。我找到了 void-Pointer,但我必须知道我通过了哪个课程。我以为那里有类似函数指针的东西,但我还没有找到。

有人知道解决方案吗?

【问题讨论】:

  • 考虑使用带有闭包、lambda 表达式的 C++11,std::function-s。使用 C++17 你会得到std::any

标签: c++ function pointers member


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 2018-03-24
    • 2021-12-31
    相关资源
    最近更新 更多