Jump to content
  • Advertisement
Sign in to follow this  

function pointers and function objects

This topic is 4494 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

Ugh I am feeling dumb. I swear I used to know this subject. I read lots of articles about them but I am still not grasping the subject. I have a class, and this class has pointers to functions that are called for various reasons, i.e events. Currently, I have them setup and working. Now due to the limitations of function pointers, such as the difference between global functions and member functions, I think I am gonna need to switch to function objects to make this class more "generalized", however I'd still want to allow pointers to functions like the way it is now. I looked at the STL functions that implement this, and they used templates...and this is the part when I am feeling dumb, how do templates accomplish this? Can I do it without templates?

Share this post

Link to post
Share on other sites
Yes, of course you can do it without templates, but it's actually easier of you don't.

The standard library handles this by having a template function that returns an instance of a templated class that takes your function, or a pointer to a member function, and holds it as a member, then calls it (or binds it to an object and calls it) through a member operator()().

Something like this.

class X;
typedef void (*pointerToFunction)(const X&);

class Functor
Functor(pointerToFunction f)
: m_f(f)
{ }

void operator()(const X& x)
{ m_f(x); }

pointerToFunction m_f;

Functor function(pointerToFunction)
return Functor(pointerToFunctioin);

std::for_each(x.begin(), x.end(), function(doIt));

As I said, it's easier of you leave it up to the standard library.

Share this post

Link to post
Share on other sites
You know what, I think I'd just stick to functors alone to keep it simple. It looks like I need to add several layers to make it accept both functions and functors.

Thanks for the help, though.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!