如何 return 一个指向函数稍微修改版本的指针?
How to return a pointer to a slightly modified version of a function?
考虑以下最小示例:
#include <stdio.h>
double square(double x);
double cube(double x);
int main(){
double (*pArray[2]) (double x) = {square, cube};
return 0;
}
double square(double x){
return (x*x);
}
double cube(double x){
return (x*x*x);
}
现在,让我们假设*我们想要一个在伪代码中会像这样的函数(请注意,+
不是真正的加法):
functionPointer funcB(y, functionPointer funcA){
functionPointer funcC = y + &funcA;
return funcC;
}
这样 funcC
与 funcA
和调用 funcC(x)
returns y + funcA(x)
具有相同的签名。我们怎样才能做到这一点?我想不出办法。
* 可能对
这样的东西有用
for(double y = 0; y < 1; y += 0.1){
for(double x = 0; x <= y; x += 0.1){
printf("%f\n", funcB(y, pArray[0])(x) );
printf("%f\n", funcB(y, pArray[1])(x) );
}
}
对于给出的示例,您不需要额外的函数指针。你可以这样做:
double funcB(double y, functionPointer funcA, double x){
return y + funcA(x);
}
...
for(double y = 0; y < 1; y += 0.1){
for(double x = 0; x <= y; x += 0.1){
printf("%f\n", funcB(y, pArray[0], x) );
printf("%f\n", funcB(y, pArray[1], x) );
}
}
您所描述的称为闭包(闭包可以看作是捕获了一些数据的匿名函数)。不幸的是,你不能在 C 中直接创建闭包1。你能得到的最接近的是 C++ 中的仿函数对象(和 lambda,这是一种用于创建仿函数的语法糖),但那些不能通常转换为函数指针。
您还可以通过引入用于维护状态的附加参数来模拟闭包。但必须明确管理该状态。
1 理论上,您可以分配一些内存,在其中写入一些机器代码,将内存标记为可执行,并创建指向该代码的函数指针。然而,这将是高度依赖于平台且非常复杂的任务。
考虑以下最小示例:
#include <stdio.h>
double square(double x);
double cube(double x);
int main(){
double (*pArray[2]) (double x) = {square, cube};
return 0;
}
double square(double x){
return (x*x);
}
double cube(double x){
return (x*x*x);
}
现在,让我们假设*我们想要一个在伪代码中会像这样的函数(请注意,+
不是真正的加法):
functionPointer funcB(y, functionPointer funcA){
functionPointer funcC = y + &funcA;
return funcC;
}
这样 funcC
与 funcA
和调用 funcC(x)
returns y + funcA(x)
具有相同的签名。我们怎样才能做到这一点?我想不出办法。
* 可能对
这样的东西有用for(double y = 0; y < 1; y += 0.1){
for(double x = 0; x <= y; x += 0.1){
printf("%f\n", funcB(y, pArray[0])(x) );
printf("%f\n", funcB(y, pArray[1])(x) );
}
}
对于给出的示例,您不需要额外的函数指针。你可以这样做:
double funcB(double y, functionPointer funcA, double x){
return y + funcA(x);
}
...
for(double y = 0; y < 1; y += 0.1){
for(double x = 0; x <= y; x += 0.1){
printf("%f\n", funcB(y, pArray[0], x) );
printf("%f\n", funcB(y, pArray[1], x) );
}
}
您所描述的称为闭包(闭包可以看作是捕获了一些数据的匿名函数)。不幸的是,你不能在 C 中直接创建闭包1。你能得到的最接近的是 C++ 中的仿函数对象(和 lambda,这是一种用于创建仿函数的语法糖),但那些不能通常转换为函数指针。
您还可以通过引入用于维护状态的附加参数来模拟闭包。但必须明确管理该状态。
1 理论上,您可以分配一些内存,在其中写入一些机器代码,将内存标记为可执行,并创建指向该代码的函数指针。然而,这将是高度依赖于平台且非常复杂的任务。