Function pointers and functor :
Syntax for Accessing function pointer in c :
int getRes(void);
int main()
{
int (*current_res)(void);
current_ans = &getRes;
// HERE
printf(“%d”, current_res());
}
Syntax – Array of function pointers :
int (*funcPtrArr2[100])(float, int, char) = {NULL};
Functor:
It’s a function object. A class object is called a functor if it has a provision of function operator. This gives class object function semantics.
A basic functor :
class MyFunctor
{
public:
int operator()(int x) { return x * 2;}
}
MyFunctor twice;
int x = twice(5);
Drawbacks of using function pointers in C:
1. A function contains no instance state, mainly because there is no such thing as multiple instances of a function; there will only ever be one instance and that is global. Although, it is possible to declare a local static within the function that can retain state between calls, but since a function only has one instance there can only be one instance of the static member and that must be shared between function calls.
A function with local static state
MyDataClass &
foo()
{
static
MyDataClass data;
// Do some work
return
data;
}
MyDataClass &
foo(Mutex m)
{
ScopedLock sl(m);
// Ensure no other thread can get in here
static
MyDataClass data;
// Do some work
return
data;
// Note once the scoped lock ends here another thread could enter
and modify data before the caller has a chance to copy it, so even this isn’t a very good solution, really the mutex should be locked by the caller.
}
3. Function pointers do not work very well with templates, if only one signature of the function exists then things will work otherwise the compiler will complain of template instantiation ambiguities that can only be resolved through ugly function pointer casting.
A function pointer casting to resolve template instantiation ambiguities
void
callback_func(
void
*){}
void
callback_func(
char
*){}
template
void
consumer(funcT callback_func)
{
}
int
main()
{
consumer(callback_func);
// ERROR: Which one?
consumer((
void
(*)(
void
*))callback_func);
consumer((
void
(*)(
char
*))callback_func);
}