Sign in to follow this  

function pointers and function objects

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this