传递一个函数(带有可变数量的参数!)作为参数

时间:2014-02-11 06:05:36

标签: c++ arguments function-pointers argument-passing

我有一个bisectionMethod函数,它接受一个函数作为它的一个参数。对于bisectionMethod的意图和目的,它接受的函数参数只有一个正在优化的参数。但是,我想将任何类型的函数(具有任意数量的参数)传递给bisectionMethod函数。我在bisectionMethod函数中使用指针函数作为参数,但它要求我确切地指定了多少参数进入该指针函数。对此最好的解决方法是什么?

例如,我正在尝试做这样的事情:

double bisectionMethod(double xMinimum, double xMaximum, double maxError, double (*rootFunc)(double))
{
    ...
    return ret;
}

double foo1(double x1, double y1){return x1 * y1;}
double foo2(double x2, double y2, double z2){return x2 * y2 * z2;}

int main(){

// I want to first be able to set y1 in foo1.
// Then I want to solve for x1
bisectionMethod(5, 250, 0.1, foo1(x1));

// I want to also be able to use bisectionMethod with foo2
// I want to first be able to set x1, and y1 in foo2.
// Then I want to solve for z1
bisectionMethod(5, 250, 0.1, foo1(z1));

return 0;

}

我希望这个例子有意义。我知道这有点奇怪。任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

#include <functional>
using namespace std;
using namespace std::placeholders;

double bisectionMethod(double xMinimum, double xMaximum, double maxError, function<double (double)>)
{
   ...   
   return ret;
}

double foo1(double x1, double y1){return x1 * y1;}
double foo2(double x2, double y2, double z2){return x2 * y2 * z2;}

int main(){

// I want to first be able to set y1 in foo1.
// Then I want to solve for x1
bisectionMethod(5, 250, 0.1, std::bind(foo1, _1, 1.0));

// I want to also be able to use bisectionMethod with foo2
// I want to first be able to set x1, and y1 in foo2.
// Then I want to solve for z1
bisectionMethod(5, 250, 0.1, std::bind(foo2, _1, 1.0, 2.0));

return 0;

}

这适用于C ++ 11.对C ++ 98使用boost :: bind。

答案 1 :(得分:0)

提升版:

#include <boost/bind.hpp>
#include <boost/function.hpp>

double bisectionMethod(double xMinimum, double xMaximum, double maxError, boost::function<double(double)>)
{
    ...
    return 0;
}

double foo1(double x1, double y1){return x1 * y1;}
double foo2(double x2, double y2, double z2){return x2 * y2 * z2;}

int main(){

  // I want to first be able to set y1 in foo1.
  // Then I want to solve for x1
  bisectionMethod(5, 250, 0.1, boost::bind(foo1, _1, y1));

  // I want to also be able to use bisectionMethod with foo2
  // I want to first be able to set x1, and y1 in foo2.
  // Then I want to solve for z1
  bisectionMethod(5, 250, 0.1, boost::bind(foo2, x1, y1, _1));

  return 0;

}