在C ++中使用std :: bind和std :: function时出错

时间:2016-11-04 14:49:37

标签: c++ c++11 std-function newtons-method stdbind

我尝试在多变量函数上尝试我的Newton方法片段并使用std::bindstd::function。但我遇到了错误

  

错误:从'std :: _ Bind_helper&,int> :: type {aka   std :: _ Bind,int))(double,double,   double)>}'到非标量类型'std :: function'   请求的

此错误消息的含义是什么?如何修复当前代码?

#include <iostream>
#include<functional>
#include<cmath>

double newton(std::function<double(double)> F, std::function<double(double)> f,
              double x=0, int maxiter=1000, double epsilon=0.001)
{
    int n = 0;
    while((n < maxiter) && (fabs(F(x)) > epsilon))
    {
        x = x - F(x) / f(x);
        n++;
    }
    return x;
}

// I'd like to fix x and z at 1 and 2 and find root for y
double ftest(double x, double y, double z) 
{
    return x * x + (y * y - 2 * y - 4) + z * z;
}

// Partial derivative of ftest with regards to y
double ftest1(double y) 
{
    return 2 * y - 2;
}

int main()
{
    using namespace std::placeholders;
    std::function<double(double)> F = std::bind(ftest, 1, _2, 2);
    std::function<double(double)> f = ftest1;
    std::cout << newton(F, f);
    return 0;
}

1 个答案:

答案 0 :(得分:4)

这里的问题:

std::function<double(double)> F = std::bind(ftest, 1, _2, 2);

F是一个函数,它接受类型double的单个参数,但你的绑定表达式涉及_2 - 它引用传递给函数对象的第二个参数{ {1}}返回。也就是说,第二个参数。基本上,你大致构建了这个函数对象:

bind()

该对象有两个参数。 struct { template <class T, class U> auto operator()(T, U arg) { return ftest(1, arg, 2); } }; 不允许这样做 - 它要求你的callable允许一个参数。

简单的解决方法是修复占位符:

std::function<double(double)>

或者,更好的是,根本不要使用std::function<double(double)> F = std::bind(ftest, 1, _1, 2); 而更喜欢lambda:

bind()