Astraeus
Astraeus

Reputation: 71

Pass non-static member function to member function of another class

I have two classes A and B. And I want to call the member function of class B from class A while passing a member function of A to said function of B. The setting:

class B {
    public:
        int dopristep(std::function<int(int,int)> f, double t, double h);
    };

class A {
public:
    
    void run();
    int g(int,int);
    B* mB;
};

void A::run() {

    ires         = mB->dopristep(&g,  T, h)   
}

int A::g(int,int){
//do something
}

I tried with std::bind and std::function definitions. But it didn't work since it requires a static member function somehow. ( I am aware that there are similar questions here. But almost all of them reside these calls in the main or inside only one class) The most similar case I could find which didn't help was here.

Can anyone please help me on how I can implement this ?

ERROR:reference to non-static member function must be called

Upvotes: 0

Views: 1064

Answers (1)

Erlkoenig
Erlkoenig

Reputation: 2754

As explained here, pass a lambda that calls the function on the enclosing A instance:

mB->dopristep([&] (int a, int b) { return g(a, b); }, T, h);

Additionally, you could modify dopristep to accept a functional which will avoid some overhead:

template <typename F>
int dopristep(F&& f, double t, double h);

Upvotes: 3

Related Questions