Functor Object Example

From FunctorObject:

Here's a stripped down version of a C++ implementation: -- PhilGoodwin

This declares an interface for functors that is used by clients. Other versions of this interface include parameter types and return values

 struct Functor
 { virtual void operator()()=0; };

This declares an adaptor that turns an object/method pair into a Functor that can be passed to a client
 template< typename Type_ >
 class FunctorFor: public Functor
 {
 public:
        typedef void(Type_::*MemberFunction)();

private: Type_ *theInstance; MemberFunction theMethod;

public: FunctorFor(Type_ *anInstance, MemberFunction aMethod): theInstance(anInstance), theMethod(aMethod){}

void operator()() { (theInstance->*theMethod)(); } };

This declares an adaptor for normal function pointers It doesn't actually do anything except add type safety
 class FunctionFunctor: public Functor
 {
 public:
        typedef void(*FunctionType)();

private: Function theFunction;

public: FunctionFunctor(FunctionType aFunction): theFunction(aFunction){}

void operator() () { theFunction(); } };

Here are a couple of snippets that show how to add parameter and return types:

 template< typename ReturnType, typename ParameterType >
 struct FunctorR1
 { ReturnType operator() (ParameterType)=0; };

template< typename Type_, typename ReturnType, typename ParameterType > class FunctorR1For: class FunctorR1<ReturnType, ParameterType> { ... typedef ReturnType(Type_::*MemberFunction)(ParameterType); ... ReturnType operator() (ParameterType param) { return (theInstance->*theMethod(param); } };


See BlocksInJava for an example in the JavaLanguage


EditText of this page (last edited June 6, 2011) or FindPage with title or text search