How can I redefine this function:
unsigned int uiTimer(int milliseconds, int (*f)(void *data), void *data)
so that it can take this function as a param (or any other function regardless of signature) ?
int filterInput(uiEditableCombobox *pBox, void *pvData)
like this:
uiTimer(1000, filterInput, NULL);
I tried wrapping filterInput in a "timerDone(void *)" but this cannot be done because I need to pass the parameters into filterInput.
int timerDone(void *) {
filterInput(); // <--- I need context to be passed as params
}
uiTimer(1000, timerDone, NULL);
Change signature to use std::function
:
#include <functional>
unsigned int uiTimer(int milliseconds, std::function<int(void*)> f, void *data)
Pass parameters using lambda expressions :
uiEditableCombobox *box;
uiTimer(1000, [=](void* data) { return filterInput(box, data); }, nullptr);
You can take any function pointer as argument this way:
template<typename R, typename... Ts>
void f(R(*functionPointer)(Ts...))
{ /* ... */ }
Unfortunately, separate case is necessary for member function pointers:
template<typename R, typename T, typename... Ts>
void f(R(T::*functionPointer)(Ts...))
{ /* ... */ }
But in essence, any function pointer will be also caught by single template parameter since it's also a valid type, but then you must be aware that you are allowing much more entities to be passed (eg not a function pointers).
template<typename T>
void f(T&& f)
{ /* ... */ }
Here is a working example that shows mutiple ways of using function pointers in template functions: http://coliru.stacked-crooked.com/a/a1a01993266e6351
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.