-
-
Save unkstar/2499156 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <list> | |
#include <iostream> | |
class FunctorBase | |
{ | |
public: | |
virtual std::string get() = 0; | |
}; | |
template<typename Ty_> | |
struct traits { | |
}; | |
template<> | |
struct traits<int> { | |
static std::string toString(int v) { | |
return "int\n"; | |
} | |
}; | |
template<> | |
struct traits<float> { | |
static std::string toString(float v) { | |
return "float\n"; | |
} | |
}; | |
template<class Object, class result_type> | |
class MemberFunctor | |
: public FunctorBase | |
{ | |
public: | |
typedef result_type(Object::*Functor)(); | |
MemberFunctor(Object *obj,Functor functor) | |
: m_Object(obj), m_Functor(functor) | |
{ | |
} | |
std::string get() { | |
return traits<result_type>::toString((m_Object->*m_Functor)()); | |
} | |
private: | |
Object *m_Object; | |
Functor m_Functor; | |
}; | |
template<class Object, class result_type> | |
MemberFunctor<Object, result_type>* make_functor(Object *obj, result_type(Object::*functor)()) | |
{ | |
return new MemberFunctor<Object, result_type>(obj, functor); | |
} | |
class TargetObject | |
{ | |
public: | |
int testInt() {return 0;} | |
float testFloat(){return 0.0;} | |
}; | |
class FunctorManager | |
{ | |
public: | |
template<class Object,class Functor> | |
void AddFunctor(Object *obj,Functor functor) | |
{ | |
FunctorBase *pFunctorBase = make_functor(obj,functor); | |
m_listFunctors.push_back(pFunctorBase); | |
} | |
void foreach() { | |
for(std::list<FunctorBase*>::iterator i = m_listFunctors.begin(); i != m_listFunctors.end(); ++i) { | |
std::cout<<(*i)->get(); | |
} | |
} | |
private: | |
std::list<FunctorBase*> m_listFunctors; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Base.h" | |
int main() | |
{ | |
TargetObject *pObject = new TargetObject; | |
FunctorManager *pFunctorManager = new FunctorManager; | |
pFunctorManager->AddFunctor(pObject,&TargetObject::testFloat); | |
pFunctorManager->AddFunctor(pObject,&TargetObject::testInt); | |
pFunctorManager->foreach(); | |
return 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment