指向参数较少的函数
Point to a function with less arguments
我有一个包含多个参数的基函数 (myfunc)。我想在主函数中选择一些参数,然后调用将使用其中的 myfunc 的例程 (some_routine)。
基本上我想要的东西
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;
}
我发现了一个类似的问题 , but it's another language... And a similar on in c++,在那个问题中,要选择的参数只是 "selector"。
您需要使用 std::bind
。详情在这里 http://en.cppreference.com/w/cpp/utility/functional/bind
所以
auto f = std::bind(myfunc, args here)
然后使用 std::function
作为方法的数据类型
我有一个包含多个参数的基函数 (myfunc)。我想在主函数中选择一些参数,然后调用将使用其中的 myfunc 的例程 (some_routine)。
基本上我想要的东西
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;
}
我发现了一个类似的问题
您需要使用 std::bind
。详情在这里 http://en.cppreference.com/w/cpp/utility/functional/bind
所以
auto f = std::bind(myfunc, args here)
然后使用 std::function
作为方法的数据类型