指向一个参数较少的函数
Point to a function with less arguments
我有一个有多个参数的基函数(myfunc)。我想在main函数中选择一些参数,然后调用一个例程(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;
}
我在fortran中发现了一个类似的问题,但它是另一种语言…在c++中也有类似的情况,在这个问题中选择的参数只是一个"selector"
您需要使用std::bind
。详情在这里http://en.cppreference.com/w/cpp/utility/functional/bind
auto f = std::bind(myfunc, args here)
则使用std::function
作为方法
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类