c ++ C ++模板中函数指针的错误C2064

时间:2011-08-02 13:57:01

标签: c++ function-pointers

如果我编译下面的代码,我会得到一个

  

“错误C2064:术语不评估为采用2个参数的函数”

doOpp()方法中的

。如果我为q = f(p, i);更改q = add(p, i);,则所有内容编译都很正常(add()方法中的doOpp()是第二个参数)。我尝试了几种解决方案但似乎没有任何解决方案。

template <class T = double>
class Points {
public: 
    Points(void);
    Points(Point3d<T> *, int);
    Points(T *, int);
    Points(Points &);
    ~Points(void);

    void clear();
    int size();
    void push_back(Point3d<T> &);
    typename vector<Point3d<T>>::iterator begin(void){return pnts.begin();};
    typename vector<Point3d<T>>::iterator end(void){return pnts.end();};

    void assign(Point3d<T> *, int);
    void assign(T *, int);
    void assign(Points &);

    Points valid(void);
    Points valid(int *);
    bool setValid(int, bool);
    int validSize();

// Pointer to operator function prototype
    typedef Point3d<T> (__thiscall Points<T>::*oppFunc) (Points<T> &, int);

    Points operator=(Points &);

// + Operator method
    Points operator+(Points &p){return doOpp(p, &Points<T>::add);};
    Points operator-(Points &){return doOpp(p, &Points<T>::sub);};
    Points operator*(Points &){return doOpp(p, &Points<T>::mlt);};;

private:

    Points(int);
    void assign(int);
    int assign(Points &, Points &);
    vector<Point3d<T>> pnts;
    bool isSameSize(Points<T> &, char *);

// General purpose operator function
    Points doOpp(Points<T> &, oppFunc);

// Addition method called by doOpp
    Point3d<T> add(Points &p, int i) {return pnts[i] + p.pnts[i];}
    Point3d<T> sub(Points &p, int i) {return pnts[i] - p.pnts[i];}
    Point3d<T> mlt(Points &p, int i) {return pnts[i] * p.pnts[i];}
};

template <class T> int
Points<T>::assign(Points &p1, Points &p2) {
    int s = min(p1.size(), p2.size());
    assign(s);

    return s;
}

template <class T> bool
Points<T>::isSameSize(Points &p, char *s) {
    bool    same = (pnts.size() == p.pnts.size());

    #ifndef POINTS_NO_THROW
    if (!same) {
        PointsException e;
        e.setMessage((string) s + " source sizes not equal");
        throw e;
    }
    #endif

    return same;
}

template <class T> Points<T>
Points<T>::doOpp(Points &p, oppFunc f) {
    isSameSize(p, __FUNCTION__);
    Points<T>   r;
    int         s = r.assign(*this, p);
    Point3d<T>  q;

    for (int i = 0; i < s; i++) {
        q = f(p, i); // Causes error C2064 but q = add(p, i); works fine
    }

    return r;
}


int
main () {
    Points<>    p, q;

    q.assign(a, 4);
    p = q + q;

    return 1;
}

2 个答案:

答案 0 :(得分:7)

由于oppFunc f是成员函数指针,您应该使用特殊语法通过成员函数指针进行调用:

q = (this->*f)(p, i);

答案 1 :(得分:0)

应该这样:

Points operator-(Points &){return doOpp(p, &Points<T>::sub);};

不是:

 Points operator-(Points &p){return doOpp(p, &Points<T>::sub);}; // note the p argument