I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?
Functors are used in gtkmm to connect some GUI button to an actual C++ function or method.
If you use the pthread library to make your app multithreaded, Functors can help you.
To start a thread, one of the arguments of the pthread_create(..)
is the function pointer to be executed on his own thread.
But there's one inconvenience. This pointer can't be a pointer to a method, unless it's a static method, or unless you specify it's class, like class::method
. And another thing, the interface of your method can only be:
void* method(void* something)
So you can't run (in a simple obvious way), methods from your class in a thread without doing something extra.
A very good way of dealing with threads in C++, is creating your own Thread
class. If you wanted to run methods from MyClass
class, what I did was, transform those methods into Functor
derived classes.
Also, the Thread
class has this method:
static void* startThread(void* arg)
A pointer to this method will be used as an argument to call pthread_create(..)
. And what startThread(..)
should receive in arg is a void*
casted reference to an instance in heap of any Functor
derived class, which will be casted back to Functor*
when executed, and then called it's run()
method.