Wednesday, December 7, 2011

The intertubes are full of examples on how to use function pointers in C/C++. Most try to simplify things by typedef'ing the function signature. What if you're a glutton for punishment like me and want to do it the "hard" way?

Ok, here's the background. Let's say you want to be able to find the cosine of an array of doubles, but you also want to be able to find the sine, tangent, etc.

So that's a bit better. Only one implementation of the loop code, simple implementations for each operation, only the overhead of an additional pointer dereference per element. How did we pull this off?

voidapply_operation(double *dat, intlength, double (*oper)(double))

apply_operation() takes a function pointer as a parameter (the last argument). This makes it so that apply_operation() can take any function that takes a single double as input and returns a single double as output. Slick.

Now, the next step: returning a function pointer (without typedefing the signature). Let's say we have a table of operations and we associate each operation type with a function pointer so that we can do a simple lookup to get a pointer to the desired operation function. So, in other words, we're returning a function pointer. Here's how to do it without a typedefed function signature.

This means that get_oper() is a function that takes a single int as a parameter and returns a function pointer to a function that returns a double and takes a single double as its only argument. Simple, right? There it is--returning a function pointer from a function without typedefing the signature (the "hard" way).