在C ++中使用std :: bind和std :: function时出错 [英] Error using std::bind and std::function in C++
问题描述
我尝试在多元函数上尝试使用牛顿方法的代码段,并使用了std::bind
和std::function
.但是我陷入了错误
I attempt to try my snippet of Newton's method on a multivariate function and used std::bind
and std::function
. But I was stuck on an error
错误:从'std :: _ Bind_helper& ;, int> :: type {aka转换 std :: __ Bind,int))(double,double, double)>}'转换为非标量类型'std :: function' 请求
error: conversion from 'std::_Bind_helper&, int>::type {aka std::_Bind, int))(double, double, double)>}' to non-scalar type 'std::function' requested
此错误消息是什么意思,我该如何修复当前代码?
What does this error message mean and how should I fix my current code?
#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;
}
推荐答案
此处的问题:
std::function<double(double)> F = std::bind(ftest, 1, _2, 2);
是F
是一个接受类型为double
的单个参数的函数,但是绑定表达式涉及_2
-指的是传递给bind()
返回的函数对象的第二个参数.即 second 参数.基本上,您将大致构造此功能对象:
is that F
is a function that takes a single argument of type double
, but your bind expression involves _2
- which refers to the second argument passed to the function object that bind()
returns. That is, the second argument. Basically, you're constructing this function object, roughly:
struct {
template <class T, class U>
auto operator()(T, U arg) {
return ftest(1, arg, 2);
}
};
该对象有两个参数. std::function<double(double)>
不允许这样做-它要求您的可调用项允许单个参数.
That object takes two arguments. std::function<double(double)>
doesn't allow for that - it requires that your callable allow for a single argument.
简单的解决方法是修复占位符:
The simple fix is to fix the placeholder:
std::function<double(double)> F = std::bind(ftest, 1, _1, 2);
或者更好的是,根本不使用bind()
而是使用lambda:
or, better, just don't use bind()
at all and prefer a lambda:
std::function<double(double)> F = [](double y) { return ftest(1, y, 2); }
这篇关于在C ++中使用std :: bind和std :: function时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!