drbombe
drbombe

Reputation: 639

Pass function member as a parameter within a class C++

Within a non-static class, can I directly pass function member rhs as below? It reports some errors. I also tried to change it as mystepper.do_step(this->rhs)It still doesn't work. But if I put mystepper.do_step(rhs); in the main function, and rhs as a function, it works fine. How can I fix this problem? Many thanks!

void Animal::rhs(const double x , double &dxdt , const double t) {    
            dxdt = 2*t;
        };

 void  Animal::response() {    
    mystepper.do_step(rhs);   
}

I made some minimalist code to illustrate my previous question.Your help is highly appreciated!!

 #include <iostream>

    using namespace std;
    class ABC{
    private:
        int x =3;
        int add2num(int a, int b){
            return a+b+x;
        }

        int worker(int &fun(int a, int b), int a, int b){
            return fun(a,b);
        }
    public:
        int doSomething(int a, int b){
            return worker(add2num, a, b);
        }
    };

    int main() {
        ABC test;
        cout << test.doSomething(3,5) << endl;
        return 0;
    }

Upvotes: 1

Views: 108

Answers (2)

zoska
zoska

Reputation: 1723

You can use lambda, so you can wrap call to class method in a function :

void  Animal::response() {    
    mystepper.do_step([&](const double x , double &dxdt , const double t) 
        { return rhs(x, dxdt, t); });   
}

But looking at your rhs function it can easily be a static class function (there are no calls to members of Animal class inside).

Upvotes: 1

roalz
roalz

Reputation: 2778

You can make the rhs() function static in your class, if it does not access any of the class member variables, as it seems in your example.

Or, if you need rhs() to be a non-static method of the class, you can use std::bind() (if your compiler is C++11 compliant) or boost::bind() to bind the class method to the class instance (i.e. "this").
See examples in this other StackOverflow answer.

Another option for C++11 compilers is to use lambda functions.

Anyway, from your source code snippet is not really clear what you want to do, and I suggest you to include a minimal yet complete source code that shows your need, as well as better define "doesn't work" and "some errors".

Upvotes: 0

Related Questions