Jump to content
  • Advertisement
Sign in to follow this  
SiS-Shadowman

Function pointers & member functions

This topic is 4250 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement
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)(); }
};


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!