简体   繁体   English

Function C++ 中的包装

[英]Function wrapper in C++

Very simply, I'm using an optimization library in C++ that takes in a function of a single variable.很简单,我在 C++ 中使用了一个优化库,它接收单个变量的 function。 I would like to be able to pass in multiple parameters though (which this library does not support).我希望能够传入多个参数(这个库不支持)。 What I would like to do is create a lambda function of the sort (kind of like in Python) that lets me represent the cost function as a function of a single variable that passes in two parameters. What I would like to do is create a lambda function of the sort (kind of like in Python) that lets me represent the cost function as a function of a single variable that passes in two parameters.

Here's a simplified version of what I'm going for in pseudocode.这是我要使用伪代码的简化版本。 Any help would be much appreciated.任何帮助将非常感激。 I can't seem to get this to work with lambda in C++.我似乎无法让它与 C++ 中的 lambda 一起使用。

Optimize comes from a library (asa047). Optimize 来自一个库(asa047)。 The version I wrote here isn't at all realistic, but is just meant to demonstrate what this function takes in.我在这里写的版本根本不现实,只是为了演示这个 function 的内容。

double cost(double x, double param1, double param2){
    return x*param1 + param2;

}

double optimize(double fn( double x), double initial_value){
    return optimal_x;

}

int main(){

    double param1 = 2;
    double param2 = 3; 
    function_object f; //What I would like to create
    f(double x){
        return cost(x,param1,param2);
    }
    optimize(f,2); 
}

What I could see under the link to the asa47 library is that the function comes with source code.我在 asa47 库的链接下可以看到 function 带有源代码。 That means you can modify its parameters to pass any additional stuff as you need.这意味着您可以根据需要修改其参数以传递任何其他内容。 I think that's the easiest and most correct way to achieve what you need.我认为这是实现您所需要的最简单和最正确的方法。 Ie if fir example you want to additional int parameter, double fn ( double x[] ) can be replaces with something like double fn ( double x[], int p) , then add int p to the "nelmin" function itself, and then modify call to fn() in the nelmin() to pass that additional p.即,如果您想添加额外的 int 参数,则可以将double fn ( double x[] )替换为double fn ( double x[], int p)之类的东西,然后将int p添加到“nelmin” function 本身,并且然后修改nelmin()中对fn()的调用以传递额外的 p。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM