Search code examples
c++function-pointersclass-members

How to pass a member function to a function used in another member function?


I found something about my problem, but I don't already understand very well. I need to do something like this:

class T
{
    double a;
public:
    double b;
    void setT(double par)
    {
        a = par;
    }

    double funct(double par1)
    {
        return par1 / a;
    } 

    void exec()
    {
        b = extfunct(funct, 10);
    }
};

double extfunct(double (*f)(double),double par2)
{
    return f(par2)+5;
}

Operation and function are only for example, but the structure is that. The reason of this structure is that I have a pre-built class which finds the minimum of a gived function (it's extfunct in the example). So I have to use it on a function member of a class. I understood the difference between pointer to function and pointer to member function, but I don't understand how to write it. Thanks, and sorry for the poor explanation of the problem.


Solution

  • Use a pointer to member function:

    struct Foo
    {
        void f(int, int) {}
        void g(int, int) {}
    
        void execute((Foo::*ptmf)(int, int), int a, int b)
        {
            // invoke
            (this->*ptmf)(a, b);
        }
    };
    

    Usage:

    Foo x;
    x.execute(&Foo::f, 1, 2);   // calls x.f(1, 2)
    x.execute(&Foo::g, 2, 1);   // calls x.g(2, 1)
    

    These pointers work as expected with virtual functions.