New Paste :: Recent Pastes:: No Line Numbers
generic functors by luke
1
// generic functors // drawbacks: // - must have exactly one argument // - cannot have a void argument (numer of arguments > 0) // - return type may not be void // ignore the 'Car' prefix #include <iostream> #include <string> #include <vector> #include "CarEventFunctor.h" #include "Dummy.h" int main(int argc, char** argv) { Dummy dummy; CarEventFunctor<Dummy, const std::vector<std::string>&, bool> efunct(&dummy, &Dummy::Print); std::vector<std::string> args; args.resize(4, "foo"); efunct(args); // Prints: // foo // foo // foo // foo return 0; } #ifndef DUMMY_H_INCLUDED_ #define DUMMY_H_INCLUDED_ #include <iostream> #include <string> #include <vector> class Dummy { public: bool Print(const std::vector<std::string>& args) { for(size_t x = 0; x < args.size(); ++x) { std::cout << args[x] << std::endl; } return true; } }; // class Dummy #endif //#ifndef DUMMY_H_INCLUDED_ #ifndef CARABSTRACTEVENTFUNCTOR_H_INCLUDED_ #define CARABSTRACTEVENTFUNCTOR_H_INCLUDED_ #include <string> #include <vector> template <typename tArg, typename tReturn> class CarAbstractEventFunctor { public: typedef tArg arg_type; typedef tReturn return_type; virtual ~CarAbstractEventFunctor() { // empty } virtual return_type operator() (arg_type args) = 0; // call using operator protected: // none private: // none }; // class CarAbstractEventFunctor #endif // #ifndef CARABSTRACTEVENTFUNCTOR_H_INCLUDED_ #ifndef CAREVENTFUNCTOR_H_INCLUDED_ #define CAREVENTFUNCTOR_H_INCLUDED_ #include <string> #include <vector> #include "CarAbstractEventFunctor.h" template <class tClass, typename tArg, typename tReturn> class CarEventFunctor : public CarAbstractEventFunctor<tArg, tReturn> { public: typedef tArg arg_type; typedef tReturn return_type; typedef return_type(tClass::*EventFunctionPtr)(arg_type); CarEventFunctor(tClass* objPtr, EventFunctionPtr funcPtr) : mObjPtr(objPtr), mFuncPtr(funcPtr) { // empty } virtual ~CarEventFunctor() { // empty } // override operator "()" virtual return_type operator()(arg_type arg) { return (*mObjPtr.*mFuncPtr)(arg); // execute member function } protected: EventFunctionPtr mFuncPtr; // pointer to function tClass* mObjPtr; // pointer to object private: // none }; // class CarEventFunctor #endif // #ifndef CAREVENTFUNCTOR_H_INCLUDED_