I like to understand how things work underneath, and I can't for the life of me figure out how changing from a function pointer to a functor actually works without error. Does the compiler detect the difference and implement different underlying machine code? For example:
Calling the function is just a matter of (*function)(params), but calling the functor is more like (*functor)(this, params). So where does this generalization occur? Does the compiler generate an anonymous wrapper for the functor/object pair that invokes the proper call?
Calling a functor (an object of a class with the function call operator overloaded) has the same semantics as a standard function call.
Note that an address_of_a function and a functor are not the same type.
So in your example above (and remembering that for_each is a template function)
for_each(c.begin(), c.end(), function); call cause the compiler to instantiate an overload of the for_each function with parameter 3 as pointer to a function.
with the functor -
an overload of the for_each function will be generated with parameter 3 as
an object of type FunctorClass
because the semantics for calling a function and a functor are the same - the generic
template code just looks like:
parameter3 () ;// function call semantics used in generic code
BUT - in the concrete code - the machine code is different because calling a standard function
and calling the function operator of a class object is different (you need the this pointer for a start).
So in summary:
The for_each function is a template function - and different concrete function code is generated
depending on whether a function pointer or a functor is used.