1

I would like to pass a member function of an instantiated object to another function. Example code is below. I am open for any strategy that works, including calling functional() from another function inside memberfuncpointertestclass using something like lambda or std::bind. Please note that I did not understand most of the threads I found with google about lambda or std::bind, so please, if possible, keep it simple. Also note that my cluster does not have C++ 11 and I would like to keep functional() as simple as it is. Thank you!

int functional( int (*testmem)(int arg) )
{
    int a = 4;
    int b = testmem(a);
    return b;
}

class memberfuncpointertestclass
{
public:
    int parm;
    int member( int arg )
    {
        return(arg + parm);
    }
};

void funcpointertest()
{
    memberfuncpointertestclass a;
    a.parm = 3;

    int (*testf)(int) = &a.member;

    std::cout << functional(testf);
}

int main()
{
    funcpointertest();
    return 0;
}
megavore
  • 127
  • 1
  • 10

2 Answers2

0

You cannot invoke a method on an object without an instance to refer to. So, you need to pass in both the instance as well as the method you want to invoke.

Try changing functional to:

template <typename T, typename M>
int functional(T *obj, M method)
{
    int a = 4;
    int b = (obj->*(method))(a);
    return b;
}

And your funcpointertest to:

void funcpointertest()
{
    memberfuncpointertestclass a;
    a.parm = 3;

    std::cout << functional(&a, &memberfuncpointertestclass::member);
}
jxh
  • 69,070
  • 8
  • 110
  • 193
0

This is a job for std::function, a polymorphic function wrapper. Pass to functional(...) such a function object:

#include <functional>

typedef std::tr1::function<int(int)> CallbackFunction;

int functional(CallbackFunction testmem)
{
    int a = 4;
    int b = testmem(a);
    return b;
}

then use std::bind to create a function object of the same type that wraps memberfuncpointertestclass::method() of instance a:

void funcpointertest()
{
    memberfuncpointertestclass a;
    a.parm = 3;

    CallbackFunction testf = std::bind(&memberfuncpointertestclass::member, &a, std::placeholders::_1);

    std::cout << functional(testf);
}

Check this item for more details.

Community
  • 1
  • 1
Yann
  • 567
  • 5
  • 15