Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a C++ function pointer on a specific object instance

I have a function pointer defined by:

typedef void (*EventFunction)(int nEvent);

Is there a way to handle that function with a specific instance of a C++ object?

class A
{
private:
    EventFunction handler;

public:
    void SetEvent(EventFunction func) { handler = func; }

    void EventOne() { handler(1); }
};

class B
{
private:
    A a;
public:
    B() { a.SetEvent(EventFromA); }  // What do I do here?

    void EventFromA(int nEvent) { // do stuff }
};

Edit: Orion pointed out the options that Boost offers such as:

boost::function<int (int)> f;
X x;
f = std::bind1st(
      std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)

Unfortunately Boost is not an option for me. Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?

like image 306
fryguybob Avatar asked Sep 30 '08 01:09

fryguybob


People also ask

How do you call a function from a pointer object?

Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);

Can a pointer point to an object?

In C++, a pointer holds the address of an object stored in memory. The pointer then simply “points” to the object. The type of the object must correspond with the type of the pointer. The & character specifies that we are storing the address of the variable succeeding it.

How do you initialize a pointer to an object of a class?

A pointer to non-static member object m which is a member of class C can be initialized with the expression &C::m exactly.

How do you pass a function pointer as an argument?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.


1 Answers

You can use function pointers to index into the vtable of a given object instance. This is called a member function pointer. Your syntax would need to change to use the ".*" and the "&::" operators:

class A;
class B;
typedef void (B::*EventFunction)(int nEvent)

and then:

class A
{
private:
    EventFunction handler;

public:
    void SetEvent(EventFunction func) { handler = func; }

    void EventOne(B* delegate) { ((*delegate).*handler)(1); } // note: ".*"
};

class B
{
private:
    A a;
public:
    B() { a.SetEvent(&B::EventFromA); } // note: "&::"

    void EventFromA(int nEvent) { /* do stuff */ }
};
like image 177
David Citron Avatar answered Oct 19 '22 23:10

David Citron