【问题标题】:Point to a function with less arguments指向一个参数较少的函数
【发布时间】: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&lt;double(double)&gt;,这很容易。
  • @bash.d 从技术上讲,部分应用。柯里化促进了这一点,但严格来说是独立的。
  • @KonradRudolph 我明白了!谢谢

标签: c++ function-pointers


【解决方案1】:

您需要使用std::bind。详情看这里http://en.cppreference.com/w/cpp/utility/functional/bind

所以

auto f = std::bind(myfunc, args here)

然后使用std::function作为方法的数据类型

【讨论】:

  • 同样的方法也可以使用 lambda 来执行:auto f = [](X x) { return myfunc(1, 2, x); }。就我个人而言,我实际上会完全按照您的建议使用std::bind,但是从我所看到的来看,SO 上的大多数人似乎更喜欢 lambdas。
猜你喜欢
  • 2021-10-20
  • 2014-04-20
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
相关资源
最近更新 更多