Search code examples
c++boostodeodeint

How to pass a class function to another within the same class?


I am using boost odeint in C++ to calculate a simple system of ODEs. Both the odesys and solver are methods of the same class. I pass the odesys as an argument to the integration function but I get a C2064 build error "term does not evaluate to a function taking 3 arguments" and refers me to an error in a library header file. Here is a sample code:

#include <boost/numeric/odeint.hpp>

using namespace boost::numeric::odeint;

typedef std::vector< double > state_type;

class myClass {
public:
    void odesys(state_type& x, state_type& dxdt, double t)
    {
        dxdt[0] = 10.0 * (x[1] - x[0]);
        dxdt[1] = 28.0 * x[0] - x[1] - x[0] * x[2];
        dxdt[2] = x[0] * x[1] - 8.0 / 3.0 * x[2];
    }
    void solver() {
        state_type x(3);
        x[0] = x[1] = x[2] = 10.0;
        const double dt = 0.01;
        integrate_const(runge_kutta4< state_type >(), &myClass::odesys, x, 0.0, 10.0, dt);
    }
};

int main() {
    myClass foo;
    foo.solver();
}

Solution

  • You should bind the object instance (e.g. this):

        integrate_const(runge_kutta4<state_type>(),
                        std::bind(&myClass::odesys, this, _1, _2, _3), x, 0.0,
                        10.0, dt);
    

    You can also use lambdas to achieve the same:

        integrate_const(
            runge_kutta4<state_type>(),
            [this](state_type& x, state_type& dxdt, double t) {
                return odesys(x, dxdt, t);
            },
            x, 0.0, 10.0, dt);
    

    See it compiling Live On Coliru