You can use operator(), also known as the 'function call operator', to make an object behave like (and be usable as) a function.
These objects are often referred to as 'functors', but that shouldn't be confused with the same term from mathematics. I believe a more proper term is 'function object'.
Imagine you have a function that takes a callback. But suppose you need to store some state in that callback.
[note: I haven't compiled this code, but you get the idea]
void DoStuffAndCallBack(MyCallbackType Callback)
{
...
Callback(args)
...
}
In C, or in 'C-with-classes'-style C++, you would pass a static callback function to this method, and store results in some global or class-static variable.
But in C++, the function could be written like so:
template<CallbackType>
void DoStuffAndCallBack(CallbackType Callback)
{
...
Callback(args)
...
}
Now you can define a functor object that overloads operator()
and pass an instance of that object to the function. That instance will get the callback, and any intermediate results you want to store can be stored in that instance.
In other words, it's a nice way to avoid globals (:
I'm sure there are other uses, but that's one good one, IMO.