【发布时间】: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