I’m looking for some guidance in terms of best practices when dealing with custom callbacks or function pointers.
I have two main use cases right now.
- I have a blocking loop inside my class that loops forever. I want an external user to be able to specify a function that gets called on each iteration of that loop.
Ex.
myClass.setLoopFunction(doStuff);
Where doStuff is a function located elsewhere that will get called on each iteration of the loop.
- I get back an int from a function that can correspond to multiple values. I want to dynamically map functions to those values so I can just do a lookup on the int I get back and then call the corresponding function.
Ex.
myFunctionMap[passedInt]();
Where the int acts as a key to lookup the correct function to call.
I know my syntax here is probably off and I will need to use a std::map and be passing pointers etc, but any help, guidance or pitfalls would be appreciated.
Thanks!
EDIT:
I have the following declared for now as a public variable:
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;
};
The functionality I want to have is that any class can pass in a function that takes in 0 arguments and returns void and I will set that as my processing function. In the while loop, I will execute that processingFunction and it will call the member function on that original class.
while(true) {
if (exitCondition == false) {
//Execute processing function
processingFunction();
}
else {
break;
}
}
I feel like I’m completely missing something with templates, std::function and/or std::bind. Then again it’s been a good four hours of scouring the internet so maybe I just need to sleep on it.
I would recommend you use
std::function< void() >instead of pointers. Note that this is a TR1 addition to the standard library, you can use Boost implementation of it to work on older implementations. The benefit of it is that it takes any kind of function that takes no arguments and returns something compatible withvoid(that is: returns anything). You can use it in conjuntion withstd::bindto get even more flexibility.That said, you would still need an
std::map< int, std::function< void() > >(or an ordinarystd::vectorif your indices are sequential) to map from indices to functions.