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

Question!

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?

By : fryguybob


Answers

You may find C++ FAQ by Marshall Cline helpful to what you're trying to accomplish.



Run away from raw C++ function pointers, and use std::function instead.

You can use boost::function if you are using an old compiler such as visual studio 2008 which has no support for C++11.
boost:function and std::function are the same thing - they pulled quite a bit of boost stuff into the std library for C++11.

Note: you may want to read the boost function documentation instead of the microsoft one as it's easier to understand



You mention that boost isn't an option for you, but do you have TR1 available to you?

TR1 offers function, bind, and mem_fn objects based on the boost library, and you may already have it bundled with your compiler. It isn't standard yet, but at least two compilers that I've used recently have had it.

http://en.wikipedia.org/wiki/Technical_Report_1
http://msdn.microsoft.com/en-us/library/bb982702.aspx



This video can help you solving your question :)
By: admin