Question

Essentially what I want is to pass a reference of a member function into another function of another class. A sample code is like this:

#include<iostream>

using namespace std;

class algorithm
{
    void (*ODE)(double * timeDeri, double * var);
    void simulation()
    {
        //use ODE to do simulation
    }
    parent(void (*someODE)(double * timeDeri, double * var))
    {
        ODE=someODE;
    }
}

class model:algorithm
{
    void specificODE(double * timeDeri, double * var)
    {
        //detail of the ODE
    }
    model() : algorithm(specificODE)
    {
        //some initialization
    }
}

int main()
{
    model a;
    a.simulation();
}

Now I know this code won't work. Because function pointer can only be used to point on static function. However, for some practical reasons, I cannot make specificODE static. So I wonder if there is a kind of pointer can help me do this. Could anyone help?

PS1, I've checked on member function pointer. That pointer is useful if what I want is to point to a member function in the same class. However in this case, the pointer should be able to point to a member function of a different class.

PS2, Define algorithm class based on the model is a work around. However, I want to make model and algorithm independent to each other. So that if I use the same algorithm on another model, I don't have to mess with the code in my algorithm class. For the same reason, I don't want to befriend the model class and the algorithm class or do anything specifically for the model class in the algorithm class.

Était-ce utile?

La solution

The correct syntax for member function is

void (algorithm::*ODE)(double * timeDeri, double * var)

As you mention, you need in fact be generic and use:

void (T::*ODE)(double * timeDeri, double * var)

So you may use CRTP for that:

template <typename T>
class algorithm
{
public:
    // You may use typedef:
    // typedef void (T::*ODE_T)(double * timeDeri, double * var);
    // ODE_T ODE;

    void (T::*ODE)(double * timeDeri, double * var);

    void simulation()
    {
        double d1, d2;

        (static_cast<T*>(this)->*ODE)(&d1, &d2);
        //use ODE to do simulation
    }

    //explicit algorithm(ODE_T someODE)
    explicit algorithm(void (T::*someODE)(double * timeDeri, double * var))
    {
        ODE = someODE;
    }
};

class model : private algorithm<model>
{
    friend algorithm<model>; // As you inherit privately from algorithm<T>.
public:
    void specificODE(double * timeDeri, double * var)
    {
        //detail of the ODE
    }
    model() : algorithm(&model::specificODE)
    {
        //some initialization
    }
};
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top