C++ 如何将参数绑定到接受函数的函数?

C++ How to bind arguments to a function which accepts a function?

我有一个函数 fx_1,它接受一个函数和其他参数。我想创建一个新函数 f1,其参数是 fx_1 的一部分。但是我不能使用 f1.

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

using namespace std;
using namespace std::placeholders;

double fun_exp(double x, double* y) {
    return exp(x) - x - 1;
};
double fx_1(function<double(double, double*)> fun,
    double x0, double* data = nullptr, int order = 4) {
    return 5.0;
};

int main() {

    auto f1 = bind(fx_1, fun_exp, _2, _3, 4);
    double* x = new double;
    *x = 6.0;
    cout << f1(3.0, x) << endl; //Compile Error

    function<double(double, double*)> f2 = bind(fx_1, fun_exp, _2, _3, 4); //Error.

    function<double(double, double*)> f3 = bind<double,
        function<double(function<double(double, double*)> fun, double, double*, int)>,
        double, double*>(fx_1, fun_exp, _2, _3, 4); //Error.

}

我认为 f1 应该接受类型 double, double* 的参数,因为 fx_1 的参数 2 和 3 的类型是 double, double *.

f2f3 中,我尝试显式设置模板参数,但它们都不起作用。

占位符编号是指将来调用绑定函数时的参数。
也就是说,bind(fx_1, fun_exp, _2, _3, 4); 是一个函数(-like),它接受三个参数并且只使用第二个和第三个,例如 f1(0, 3.0, x).

(如果他们引用了您绑定的函数,则不需要任何编号。)

使用 _1_2 或(更具可读性且效率不低)lambda 函数。

bind() 的占位符表示传递给创建的新函数的参数,因此您的“_2、_3”应该是“_1、_2”