Function Object:
In simple term we can define as :A Function Object, or Functor (the two terms are synonymous) is simply any object that can be called as if it is a function. An ordinary function is a function object, and so is a function pointer; more generally, so is an object of a class that defines operator().
A very simple example can be :-
class DeleteObject{
public:
template<typename T>
void operator() ( const T& ptr) const { delete ptr; }
};
vector<Drive *> vec; // our supposed definition of vector
Above functor can be used with for_each as :
for_each(vec.begin(), vec.end(), DeleteObject());
here on each element of vec, delete operator will be invoked.
and every thing is fine, assuming after for_each vec.clear() is called.
if we change the definition of DeleteObject as follow:
class DeleteObject{
public:
template<typename T>
void operator() ( const T* ptr) const {
cout << "del "<< endl; delete ptr;
}
};
and perform the same operation as above, things work fine again.
Now we change our definition as :
class DeleteObject{
public:
template<typename T>
void operator() ( const T& ptr) const { delete ptr; }
template<typename T>
void operator() ( const T* ptr) const {
cout << "del "<< endl; delete ptr;
}
};
and perform the same operation as above, things work fine again and void operator() ( const T& ptr) get invoked and it worked fine.
Now my question that is puzzling me how compiler decide which one to invoked from:
void operator() ( const T& ptr) const;
void operator() ( const T* ptr) const ;
and what difference these make?
any suggestion and response will be highly appriciated.
Very interesting post! I work for a new social blogging site called glipho.com, and was just wondering if you would be interested in sharing your posts there with us? It wouldn't change your blog in any way, and I know there are many aspiring programmers and developers who would love to read through your work here. Let me know what you think!
ReplyDeleteAll the best,
Teo