Skip to main content
gamedev.net
🔒 Locked

function pointers and function objects

Started by alnite Apr 1, 2006 at 6:49 PM 2 replies 550+ views
Original Post
alnite
alnite
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?
Bregma
Bregma
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); }private:  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.
Stephen M. Webb
Professional Free Software Developer
alnite
alnite
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.