Function pointers & member functions

Started by
2 comments, last by Julian90 17 years ago
I am using function pointers for some aspects of my game. My Console class has a RegisterCommand() function, that will save a pointer to a function, and will call this function if the appropriate name will be typed into the console. This works fine for non-member functions, but what can I do if I want to register a member function of a class? I know that I can create something like this:

CMyClass *pointer_to_member;

void myfunc()
{
    pointer_to_member->myfunc();
}

void anotherfunction()
{
    myconsole->register( myfunc );
}

This way seems to be ugly in my eyes, although it works. Can I solve this problem in another way?
Advertisement
google: member function pointer (first hit)
member function pointers

.
http://www.8ung.at/basiror/theironcross.html
You have to specify which class instance the function is called on, which will ultimately amount to what you proposed anyway given the proposed signature for the registration function.

A better approach would be to alter the registration function signature and use a functor to emulate closures:

class Functor{public:  virtual void operator()() = 0;};template <typename T>class CallMember : public Functor{  void T::(*member)();  T& target;public:  CallMember(T& target, void T::(*member)()) : target(target), member(member) {}  void operator()() { target.(*member)(); }};  
Recomended links: boost.function and boost.bind

This topic is closed to new replies.

Advertisement