【发布时间】:2015-08-16 11:26:58
【问题描述】:
我有一个包含多个参数的基本函数 (myfunc)。我想在主函数中选择一些参数,然后调用一个例程(some_routine),它将在其中使用 myfunc。
基本上我想要一些可以制作的东西
myfunc(1.,2.,x) turns to f(x)
有没有办法做到这一点?
跟随示例代码
#include<iostream>
using namespace std;
//The function
double myfunc(double tau, double chi, double phi){
double value;
//complicated process using tau, chi and x to find value.
value = tau+chi+phi;//just to work
return value;
}
//The Routine
typedef double (*function_pointer)(double);
double some_routine(function_pointer f){
// process, like finding a minimum, using some generic funcion like f(x)
double value;
double x=10;
value = f(x)*f(x);//just to work
return value;
}
//The problem
int main(){
for(double i=0.;i<10;i+=.5){
cout << some_routine(myfunc,i,i+.1) << endl;
}
//I would like to call like that. Declaring that in "some_routine" f(x):=myfunc(1,0,x)
return 0;
}
我发现了一个类似的问题in fortran,但它是另一种语言......在in c++ 上也有类似的问题,在那个问题中,要选择的参数只是一个“选择器”。
【问题讨论】:
-
听起来像是在骂我?
-
这对于函数指针来说是不可能的。另一方面,如果您让
some_routine采用任何可调用值(通过将其设为模板或采用std::function<double(double)>,这很容易。 -
@bash.d 从技术上讲,部分应用。柯里化促进了这一点,但严格来说是独立的。
-
@KonradRudolph 我明白了!谢谢
标签: c++ function-pointers