c++中使用std::bind和std::函数出错
Error using std::bind and std::function in C++
我尝试在多元函数上尝试牛顿方法的片段,并使用std::bind
和std::function
。但是我被一个错误卡住了
错误:从'std::_Bind_helper&, int>::type {aka .}转换std::_Bind, int))(双精度,双精度,到非标量类型'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;
}
这里的问题是:
std::function<double(double)> F = std::bind(ftest, 1, _2, 2);
是F
是一个接受单个double
类型参数的函数,但是您的绑定表达式涉及_2
-它引用传递给bind()
返回的函数对象的第二个参数。也就是第二个参数。基本上,您正在构造这个函数对象,大致如下:
struct {
template <class T, class U>
auto operator()(T, U arg) {
return ftest(1, arg, 2);
}
};
该对象接受两个实参。std::function<double(double)>
不允许这样做——它要求你的可调用对象允许一个参数。
std::function<double(double)> F = std::bind(ftest, 1, _1, 2);
或者,更好的是,根本不使用bind()
,而使用lambda:
std::function<double(double)> F = [](double y) { return ftest(1, y, 2); }
相关文章:
- 使用std::函数映射对象方法
- 可组合的lambda/std::函数与std::可选
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- std::函数常量正确性未遵循
- 具有变量Number of Arguments的std::函数的矢量
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 如何将类 1 的 std::函数绑定到类 2 的函数?
- 如何制作可以接受任何类型的参数的 std::函数和 lambda
- 如何将 STL 队列推送函数绑定到 std::函数?
- std::函数不起作用,但普通的旧函数指针可以 - 为什么?
- 获取 std::函数以推断按引用传递/按值传递
- std::bind 和 std::函数术语不值为接受 0 个参数?
- 从其存储的回调中删除 std::函数是否安全
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 创建一个带有 lambda 的 std::函数,而不知道函数的参数
- std::函数的解释
- 在调用过程中删除 std::函数