Search code examples
c++functionclasspointersfunction-pointers

Function pointer c++


I am trying to use a function pointer on functions of class DPkDispersionMemNK.

I don't understand why it doesn't work

Can you help me please?

the code in DPkDispersionMemKN.hpp :

#include "DPkDispersion.hpp"

class DPkDispersionMemKN : public DPkDispersion {
protected:

    float** matrixDP;
    std::pair<float,int> (DPkDispersionMemKN::*func)(int k, int i);

public:
    std::pair<float,int> computeDich(int k, int i);
    std::pair<float,int> computeSum(int k, int i);
    std::pair<float,int> computeMin(int k, int i);

    void setfunc( std::pair<float,int> (&fonction)(int, int)) { func= fonction;};
};

and the 3 functions I wish I could use a pointer on them: (they are in the DPkDispersionMemKN.cpp) (it's not really important)

std::pair<float,int> DPkDispersionMemKN::computeSum(int k, int i) {
    float max=0;
    int ind= 0;

    for (int j = k - 1; j <= i - 1; j++ ) {
        if (matrixDP[k-1][j] + dist(j, i) > max) {
            max = matrixDP[k-1][j] + dist(j, i);
            ind = j;
        }
    }

    return make_pair(max,ind);
}

std::pair<float,int> DPkDispersionMemKN::computeMin(int k, int i) {
    float max=0;
    int ind= 0;

    for (int j = k - 1; j <= i - 1; j++) {
        if (min(matrixDP[k-1][j], dist(j, i)) > max){
            max = min(matrixDP[k-1][j], dist(j, i));
            ind = j;
        }
    }

    return make_pair(max,ind);
}

std::pair<float,int> DPkDispersionMemKN::computeDich(int k, int i) {
    int j;
    int a=k-1;
    int b = i-1;
    while (b-a >= 2) {
        j = (i+(a+b)) / 2;

        if (matrixDP[k-1][j]-dist(j, i) > 0) {
            b = j;
        } else {
            a = j;
        }
    }

    if (min(matrixDP[k-1][a], dist(a, i)) < min(matrixDP[k-1][b], dist(b, i))) {
        return make_pair(min(matrixDP[k-1][b], dist(b, i)), b);
    } else {
        return make_pair(min(matrixDP[k-1][a], dist(a, i)), a);
    }
}

and Finaly, in the main.cpp:

solver3.setfunc(&DPkDispersionMemKN::computeMin);

I wish I could choose in the main witch function I want to use but it's not working.

Thank you for your help!

In file included from DPkDispersionMemKN.cpp:1:
./DPkDispersionMemKN.hpp:35:68: error: assigning to 'std::pair<float, int>
      (DPkDispersionMemKN::*)(int, int)' from incompatible type
      'std::pair<float, int> (int, int)'
  ...setfunc( std::pair<float,int> (&fonction)(int, int)) { func= fonction;};
                                                                  ^~~~~~~~

Solution

  • You need:

    void setfunc(std::pair<float,int> (DPkDispersionMemKN::*fonction)(int, int)) { func = fonction;}
    

    And usage similar to:

    std::pair<float, int> res = (this->*func)(someI, someJ);