I have understood the use of functors and how it works. But i am unable to undertand the following:
What it means exactly when someone says "function objects have a state" ? Is this state not possible to maintain with normal functions? Can somebody explain with an example?
When to prefer what: Function pointers vs functors vs normal functions?
1 What it means exactly when someone says "function objects have a state" ? Is this state not possible to maintain with normal functions?
It's not clear to me whether you mean "functions" or "functor objects" when you say "function objects".
Functions don't have state unless they have a static
variable defined in the function scope. Example:
int getNextID()
{
static int nextId = 0;
return ++nextId;
}
However, functor objects -- i.e. instances of classes that are functors -- may have state, and many do. Example:
struct PrintFunctor
{
PrintFunctor(std::ostream& out) : out_(out) {}
template <typename T>
void operator()(T const& obj) { out_ << obj << " "; }
std::ostream& out_;
};
which can be used as:
PrintFunctor f(std::cout);
std::vector<int> v = { 1, 2, 3 };
std::for_each(v.begin(), v.end(), f);
You may want to note that since function's state is static
it is shared with all calls of the function whereas you can have multiple functors that do the same thing but have different state. (Thanks are due to Nathan Oliver for bringing it up).
2 When to prefer what: Function pointers vs functors vs normal functions?
I don't see any difference between function pointers and normal functions. I am not sure what you meant by that.
My recommendation: