在处理自定义回调或函数指针时,我正在寻找最佳实践方面的一些指导.
我现在有两个主要用例.
防爆.
myClass.setLoopFunction(doStuff);
Run Code Online (Sandbox Code Playgroud)
doStuff是位于其他地方的函数,它将在循环的每次迭代中被调用.
防爆.
myFunctionMap[passedInt]();
Run Code Online (Sandbox Code Playgroud)
其中int充当查找正确函数的键.
我知道我的语法可能已关闭,我将需要使用std :: map并传递指针等,但任何帮助,指导或陷阱都将不胜感激.
谢谢!
编辑:
我现在将以下声明为公共变量:
class Window {
public:
//The processing function can be from any class and takes in no arguments and returns void
template<class T>
std::function<void(T*, void)> processingFunction;
};
Run Code Online (Sandbox Code Playgroud)
我想要的功能是任何类都可以传入一个接受0参数并返回void的函数,我会将其设置为我的处理函数.在while循环中,我将执行该processingFunction,它将调用该原始类的成员函数.
while(true) {
if (exitCondition == false) {
//Execute processing function
processingFunction();
}
else {
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我觉得我完全错过了模板,std :: function和/或std :: bind的东西.然后,这是一个很好的四个小时的互联网搜索,所以也许我只需要睡在它上面.
我建议你使用std::function< void() >而不是指针.请注意,这是标准库的TR1添加,您可以使用它的Boost实现来处理旧的实现.它的好处是它采用任何类型的函数不带参数并返回兼容的东西void(即:返回任何东西).您可以结合使用它std::bind以获得更大的灵活性.
也就是说,你仍然需要一个std::map< int, std::function< void() > >(或者一个普通的,std::vector如果你的索引是连续的)从索引映射到函数.