c++ primer笔记16: pointer to function

1. Pointers to Functions

A function’s type is determined by its return type and its parameter list. A function’s name is not part of its type:

// pf points to function returning bool that takes two const string references
bool (*pf)(const string &, const string &);

// The parentheses around *pf are necessary
// declares a function named pf that returns a bool*
bool *pf(const string &, const string &);

typedef bool (*cmpFcn)(const string &, const string &);

2. Initializing and Assigning Pointers to Functions

When we use a function name without calling it, the name is automatically treated as a pointer to a function.

cmpFcn pf1 = lengthCompare;  \\  automatically converted to a function pointer
cmpFcn pf2 = &lengthCompare;

string::size_type sumLength(const string&, const string&);
bool cstringCompare(char*, char*);
// pointer to function returning bool taking two const string&
cmpFcn pf;
pf = sumLength; // error: return type differs

A pointer to a function can be used to call the function to which it refers. We can use the pointer directly there is no need to use the dereference operator to call the function

cmpFcn pf = lengthCompare;
lengthCompare("hi", "bye"); // direct call
pf("hi", "bye"); // equivalent call: pf1 implicitly dereferenced
(*pf)("hi", "bye"); // equivalent call: pf1 explicitly dereferenced

3. Function Pointer Parameters

// third parameter is a function type and is automatically treated as a pointer to function
void useBigger(const string &, const string &,
bool(const string &, const string &))
;


// equivalent declaration: explicitly define the parameter as a pointer to function
void useBigger(const string &, const string &,
bool (*)(const string &, const string &))
;

4. Returning a Pointer to Function

int (*ff(int))(int*, int), The best way to read function pointer declarations is from the inside out, starting with the name being declared. Typedefs can make such declarations considerably easier to read:

// PF is a pointer to a function returning an int, taking an int* and an int
typedef int (*PF)(int*, int);
PF ff(int); // ff returns a pointer to function

We can define a parameter as a function type. A function return type must be a pointer to function; it cannot be a function. An argument to a parameter that has a function type is automatically converted to the corresponding pointer to function type. The same conversion does not happen when returning a function:

// func is a function type, not a pointer to function!
typedef int func(int*, int);
void f1(func); // ok: f1 has a parameter of function type
func f2(int); // error: f2 has a return type of function type
func *f3(int); // ok: f3 returns a pointer to function type