C++指针“未知”类
问题描述:
我写了一个特殊的类,它检查一些外部的东西的一些状态,如果有什么改变,我想调用回调函数。 这些函数不应该只是一个全局函数而不是一个特殊类的函数。 为了说明我的意思这里是一些代码:C++指针“未知”类
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,但是我必须知道我通过了哪个类。我以为有些东西就像我没有找到的函数指针那样。
有人知道解决方案吗?
答
我用boost :: signal2来匹配我的用例。 A tutorial for boost::signal2 is found here。
该信号只能调用函数。不在特殊对象上运行。存在通过使用boost :: bind()的一个解决方法,如:
boost::bind(boost::mem_fn(&SpecialClass::memberFunctionOfTheClass), PointerToTheObjectOfSepcialClass, _1)
的_1是它创建了一个函数(参考),它需要一个参数的占位符。您可以添加更多占位符以使用更多参数。
考虑使用带闭包,lambda表达式,'std :: function'-s的C++ 11。用C++ 17,你可以得到[std :: any](http://en.cppreference.com/w/cpp/utility/any) –