Just as with arrays (§ 6.2.4, p. 214), we cannot define parameters of function type but can have a parameter that is a pointer to function. As with arrays, we can write a parameter that looks like a function type, but it will be treated as a pointer:
// third parameter is a function type and is automatically treated as a pointer to function
void useBigger(const string &s1, const string &s2,
bool pf(const string &, const string &));
// equivalent declaration: explicitly define the parameter as a pointer to function
void useBigger(const string &s1, const string &s2,
bool (*pf)(const string &, const string &));
When we pass a function as an argument, we can do so directly. It will be automatically converted to a pointer:
// automatically converts the function lengthCompare to a pointer to function
useBigger(s1, s2, lengthCompare);
As we’ve just seen in the declaration of useBigger
, writing function pointer types quickly gets tedious. Type aliases (§ 2.5.1, p. 67), along with decltype
(§ 2.5.3, p. 70), let us simplify code that uses function pointers:
// Func and Func2 have function type
typedef bool Func(const string&, const string&);
typedef decltype(lengthCompare) Func2; // equivalent type
// FuncP and FuncP2 have pointer to function type
typedef bool(*FuncP)(const string&, const string&);
typedef decltype(lengthCompare) *FuncP2; // equivalent type
Here we’ve used typedef
to define our types. Both Func
and Func2
are function types, whereas FuncP
and FuncP2
are pointer types. It is important to note that decltype
returns the function type; the automatic conversion to pointer is not done. Because decltype
returns a function type, if we want a pointer we must add the *
ourselves. We can redeclare useBigger
using any of these types:
// equivalent declarations of useBigger using type aliases
void useBigger(const string&, const string&, Func);
void useBigger(const string&, const string&, FuncP2);
Both declarations declare the same function. In the first case, the compiler will automatically convert the function type represented by Func
to a pointer.