Search code examples
c++functor

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!


Solution

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