简体   繁体   中英

Function wrapper in C++

Very simply, I'm using an optimization library in C++ that takes in a function of a single variable. 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.

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++.

Optimize comes from a library (asa047). The version I wrote here isn't at all realistic, but is just meant to demonstrate what this function takes in.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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