Functors--仿函数
4 Functors to encapsulate C and C++ Function Pointers
4.1 What are Functors ?
Functors are functions with a state. In C++ you can realize them as a class with one or more private members
to store the state and with an overloaded operator6 () to execute the function. Functors can encapsulate C and
C++ function pointers employing the concepts templates and polymorphism. You can build up a list of pointers
to member functions of arbitrary classes and call them all through the same interface without bothering about
their class or the need of a pointer to an instance. All the functions just have got to have the same return-
type and calling parameters. Sometimes Functors are also known as Closures. You can also use Functors to
implement callbacks.
4.2 How to Implement Functors ?
First you need a base class TFunctor which provides a virtual function named Call or a virtually overloaded
operator () with which you will be able to call the member function. It’s up to you if you prefer the overloaded
operator or a function like Call. From the base class you derive a template class TSpecificFunctor which
is initialized with a pointer to an object and a pointer to a member function in its constructor. The derived
class overrides the function Call and/or the operator () of the base class: In the overrided versions
it calls the member function using the stored pointers to the object and to the member function.
//-----------------------------------------------------------------------------------------
// 4.2 How to Implement Functors
// abstract base class
class TFunctor
{
public:
// two possible functions to call member function. virtual cause derived
// classes will use a pointer to an object and a pointer to a member function
// to make the function call
virtual void operator()(const char* string)=0; // call using operator
virtual void Call(const char* string)=0; // call using function
};
// derived template class
template <class TClass> class TSpecificFunctor : public TFunctor
{
private:
void (TClass::*fpt)(const char*); // pointer to member function
TClass* pt2Object; // pointer to object
6If you prefer you can also use a function called Execute or something like that.
public:
// constructor - takes pointer to an object and pointer to a member and stores
// them in two private variables
TSpecificFunctor(TClass* _pt2Object, void(TClass::*_fpt)(const char*))
{ pt2Object = _pt2Object; fpt=_fpt; };
// override operator "()"
virtual void operator()(const char* string)
{ (*pt2Object.*fpt)(string);}; // execute member function
// override function "Call"
virtual void Call(const char* string)
{ (*pt2Object.*fpt)(string);}; // execute member function
};