Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Pass a Member Function to a Function Pointer?

class Child;
class Parent
{
public:
  void (*funcPointer)();
  void (*funcPointer2)(Parent* _this);
  void (Child::*funcPointer3)();
};

class Child: public Parent
{
public:
  void TestFunc(){

  }
  void Do(){
    Parent p;
    p.funcPointer=TestFunc; // error, '=': cannot convert from 'void (__thiscall Child::* )(void)' to 'void (__cdecl *)(void)'
    p.funcPointer2=TestFunc; // error too, '=': cannot convert from 'void (__thiscall Child::* )(void)' to 'void (__cdecl *)(Parent *)'
    p.funcPointer3=TestFunc; //this works
    p.funcPointer3=&Child::TestFunc; // this works too.
    p.funcPointer3();    // error, term does not evaluate to a function taking 0 arguments
  }
};

How can I pass a member function to a function pointer, and then how would I then call that function pointer?

like image 752
lovespring Avatar asked Nov 28 '10 10:11

lovespring


2 Answers

You can't. You either pass a pointer to a static method or Parent has to accept also a pointer to the object.

You might want to look at boost::bind and boost::function for that:

#include <boost/bind.hpp>
#include <boost/function.hpp>
struct Y
{
    void say(void) { std::cout << "hallo!";}

    boost::function<void()> getFunc() { return boost::bind(&Y::say, this); }
};

struct X
{
    //non-boost:
    void (Y::*func)();
    Y* objectY;
    void callFunc() { (objectY->*func)(); }

    //boost version:
    boost::function<void()> f;

};


X x;
Y y;
x.f = boost::bind(&Y::say, boost::ref(y));
x.f = y.getFunc();
x.f();
x.func = &Y::say;
x.objectY = &y; 
x.callFunc();
like image 156
Philipp Avatar answered Sep 19 '22 00:09

Philipp


In response to your last edit, to form a pointer-to-member, you have to use & and classkey::. There's no equivalent to the function name to pointer-to-function implicit conversion for normal functions.

// not valid:
p.funcPointer3=TestFunc;

// valid:
p.funcPointer3 = &Child::TestFunc;

To access a member through a pointer-to-member you have to use either the .* or ->* operator.

E.g.

(this->*p.funcPointer3)();
like image 43
CB Bailey Avatar answered Sep 17 '22 00:09

CB Bailey