书上说
函数可以直接返回一个可调用对象
可调用对象包括函数,函数指针等
所以函数可以直接返回一个函数。我怎么好像从来没见过?你们能举个例子给我看看吗?
还有函数返回lambda的例子
高洛峰2017-04-17 13:00:41
A pointer to a function, such as
int (*p)(int, int);
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.
PHP中文网2017-04-17 13:00:41
Callable objects mainly include function pointers, std::function and classes/structures that overload the meta bracket operator.