function pointers to user-defined functions
-
Hi, I'm trying to construct a library which features a class that should be able take a pointer to any user-defined function (preferably in a user-friendly way). Now, I've tried a templated approach which seems to work, but inheriting from template classes seems rather a pain and dito for all the different function pointer types. Small example:
#pragma once // Functor interface class template < typename _TReturn, typename _TArg> class IExecute { public: // WARNING: USE OF TYPE void AS ARGUMENT TYPE IS NOT SUPPORTED! (REQUIRES MORE DERIVED CLASSES) typedef typename _TReturn _return_type; // Interface functor return type typedef typename _TArg _arg_type; // Interface functor parameter type typedef void _class_type; // Dummy required for template consistency virtual ~IExecute(void) = 0; virtual _TReturn Execute(_TArg _Arg) = 0; // Interface functor execute function }; // Interface functor inline pure virtual destructor defined template < typename _TReturn, typename _TArg> inline IExecute< _TReturn, _TArg >::~IExecute(void) { } // Functor derived class for pointers to functions that are non-const class or namespace members (const members REQUIRES MORE DERIVED CLASSES) template < typename _TClass, typename _TReturn = unsigned int, typename _TArg = void * > class CExecuteMember : public IExecute < _TReturn, _TArg > { protected: // _ptr_type is a typedef for a pointer to a class member function of which the return and parameter type // are defined at instantiation of CExecuteMember. If multiple return or parameter values are required use a // struct pointer instead typedef _return_type (_TClass::*_ptr_type)(_arg_type); // Derived functor pointer-to-function type typedef typename _TClass _class_type; // Override for derived functor class type _class_type * m_lpClass; // Derived functor class pointer _ptr_type m_lpRoutine; // Derived functor pointer-to-function public: CExecuteMember(void) : m_lpClass(NULL), m_lpRoutine(NULL) { } CExecuteMember(_class_type * _Class, _ptr_type _Routine) : m_lpClass(_Class), m_lpRoutine(_Routine) { } ~CExecuteMember(void) { } _return_type Execute(_arg_type _Arg) // Execute a class member function { if (this->m_lpRoutine == NULL) throw std::runtime_error("No routine pointer exists"); if (this->m_lpClass == NULL) throw std::runtime_error("No class pointer exists"); return (m_lpClass->*m_lpRoutine)(_Arg);