p is a pointer to a function. This function has two parameters of type int and returns int.
A function that returns a function pointer can be defined in the following two ways.
Direct definition
int (*foo(char c))(int, int);
Use typedef
typedef int OP(int, int);
OP* foo(char c);
The two methods are equivalent, and the second one is easier to see clearly.
returns a pointer to the function.
Application examples
int foo_plus(int a, int b)
{
return a + b;
}
int foo_multiply(int a, int b)
{
return a * b;
}
typedef int OP(int, int);
OP* foo(char c)
{
OP* p;
switch(c) {
case 'p':
p = foo_plus;
break;
case 'm':
p = foo_multiply;
break;
default:
p = foo_multiply;
}
return p;
}
int main()
{
OP* f;
int n;
f = foo('p');
n = f(1, 2);
printf("%d", n); // 3
f = foo('m');
n = f(1, 2);
printf("%d", n); // 2
return 0;
}
Supplement: The function returns an object, which can be called.
A function object, that is, an object that overloads the bracket operator "()". e.g.
class A{
public:
int operator()(int x, int y)
{
return x + y;
}
}; A a; a(1, 2); has the same effect as foo_plus(1, 2); above.
A pointer to a function, such as
p is a pointer to a function. This function has two parameters of type int and returns int.
A function that returns a function pointer can be defined in the following two ways.
Direct definition
Use typedef
The two methods are equivalent, and the second one is easier to see clearly.
returns a pointer to the function.
Application examples
Supplement:
The function returns an object, which can be called.
A function object, that is, an object that overloads the bracket operator "()".
e.g.
class A{
};
A a;
a(1, 2); has the same effect as foo_plus(1, 2); above.
Callable objects mainly include function pointers, std::function and classes/structures that overload the meta bracket operator.