简体   繁体   中英

Passing member function (non-static) as a parameter to template function

I am trying to define a pointer to non-static member function, and pass the pointer along with class object to a template function, which will again send the member function for template struct operation. It keeps giving me type mismatch errors. Please help!

Clarify: 'vecfunc' is a non-static member function of class PTSolver. It takes as input vector and outputs vector. I want to pass a pointer to this vecfunc as a parameter to template function 'newt', which will also pass down to the template struct operation 'fmin().' All throughout the passing processes, I need to give information about PTSolver object 'ptsolver' since it's not a static member function. But I am not able to do this...

    template <class T>
    struct NRfmin {
        VecDoub fvec;
        T &func;
        int n;
        NRfmin(T &funcc) : func(funcc) {}
        double operator() (VecDoub_I &x) {
        n=x.size();
        double sum=0.0;
        fvec=func(x);
        for (int i = 0;i<n;i++) sum += SQR(fvec[i]);
        return 0.5*sum;
        }
    };

    template <class T>
    void newt(VecDoub_IO &x, bool &check, T &vecfunc, PTSolver &obj){
        NRfmin<T> fmin(obj.*vecfunc);
        VecDoub &fvec=fmin.fvec;
        f=fmin(x);
        ...
    }

    class PTSolver {
    public:
        PTSolver() = default;
        virtual ~PTSolver() = default;
        void solve();
        VecDoub vecfunc(VecDoub_I);
    };

    VecDoub PTSolver::vecfunc(VecDoub_I x) {
        int n=x.size();
        VecDoub results(n);
        for (int i=0;i<n;i++) {
            results[i]=2.0*x[i];
        }
        return results;
    }

    int main() {
        VecDoub initGuess(2);
        initGuess[0]=4.4;
        initGuess[1]=5.5;
        bool check;

        //function<VecDoub(PTSolver*, VecDoub_I)> Func=&PTSolver::vecfunc;
       typedef VecDoub (PTSolver::*PMemFnc)(VecDoub_I x);
       PMemFnc Func;
       PTSolver ptsolver;
       newt<PMemFnc>(initGuess, check, Func, ptsolver);
       return 0;
     }

You have a type mismatch:

template <class T>
struct NRfmin {
    NRfmin(T &funcc) : func(funcc) {}
};

template <class T>
void newt(VecDoub_IO &x, bool &check, T &vecfunc, PTSolver &obj){
    NRfmin<T> fmin(obj.*vecfunc);
    ..
};

In both cases T is a pointer to member function, but you're constructing fmin with something that is definitely not a T& (it isn't even a valid expression). Either you meant to just forward the pointer, in which case:

NRfmin<T> fmin(vecfunc);

Or you want to pass NRfmin a bound functor.

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