Functors as replacement for callback?
I've read a few articles around the web (and some of the posts on this forum) about functors and using them as a better alternative to function pointers. But I'm having a little difficulty understanding how to put them to effective use. The understanding I have so far in terms of using a functor to replace a function call is to use a functor to call a function from the class whos function I want called:
Code:
// Mostly psuedo code, probably doesn't compile, this is just about my understanding,
// not intended to be an example of actual code.
class Foo
{
public:
void functionToCall()
{
// Do Something
}
};
class Functor
{
public:
Functor(Foo &foo) : foo(foo)
{}
void operator() (void)
{
foo.functionToCall();
}
private:
Foo &foo;
};
class Bar
{
public:
void invoker(Functor functor)
{
functor();
}
};
int main()
{
Foo myFoo;
Functor myFunctor(myFoo);
Bar myBar;
myBar.invoker(myFunctor);
return 0;
}
Is this how functors are intended to be used as a better alternative to callback functions? This seems a bit overkill but then it could just be that it's a very small (and simple) example. I was originally going to use function pointers but not only are those are a nightmare to deal with when it comes to C++ classes the syntax becomes hideous and hard to understand (e.g., error prone).