Monday, April 30, 2012

C++ functors: which one will be invoked ?


Function Object:

In simple term we can define as :
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.