I have always been a bit stumped when I read other peoples' code which had typedefs for pointers to functions with arguments. I recall that it took me a while to get around to such a definition while trying to understand a numerical algorithm written in C a while ago. So, could you share your tips and thoughts on how to write good typedefs for pointers to functions (Do's and Do not's), as to why are they useful and how to understand others' work? Thanks!
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts. When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.
So for example assume you have a function:
then the following typedef:
can be used to point to this
doMulitplication
function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly namept2Func
. Note thatpt2Func
can point to ANY function which returns a float and takes in 2 floats.So you can create a pointer which points to the doMultiplication function as follows:
and you can invoke the function using this pointer as follows:
This makes good reading: http://www.newty.de/fpt/index.html