简体   繁体   中英

C++ pass function into functor

I have a problem with the using of functors. Below shows a functor that takes any functions and returns its function value and derivatives.

template <class T>
struct Funcd {
    T &func;
    double f;
    Funcd(T &funcc) : func(funcc) {}
    double operator() (double &x)
    {
        return f=func(x);
    }

    void df(double &x, double &df)
    {
        ...
    }
};

Assume I already have a function like

double FunctionA(double &x){
    return x*x;
}

My question is that I don't know how to make use of this functor. Can anyone make an example in the main function that uses this functor to find function value and derivative? Thanks!

You add it to the functor when you create it. Using the same function names as in your example I would do the following:

Funcd fd(FunctionA);

then you can you fd as a function:

double v = fd(2);

It could be that you have to specify the template argument when creating fd though, I haven't compiled or tested this code.

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