#ifndef TEMPLATE_STRUCT_H #define TEMPLATE_STRUCT_H #include #include #include namespace template_pattern { template struct TemplateBase { private: typedef void (*FP1)( void*, void* ); public: template TemplateBase( T& t) : p_(&t), fn_(&functions::processImpl) {} void operator()() { assert(p_); assert(fn_); fn_(this, p_); } private: template struct functions { static void processImpl( void* a, void* p ) { TT* t = static_cast< TT*>(p); ( *static_cast< TEMPLATE_CONCEPT*>(a) )(t); } }; void* p_; FP1 fn_; }; class ITemplate { private: typedef void (*FP1)( void* ); public: template ITemplate(T& x) : p_(&x), fn_(&functions::dispatchImpl) {} void operator()() { fn_(p_); } private: template struct functions { static void dispatchImpl( void* a ) { ( *static_cast< TT*>(a) )(); } }; void* p_; FP1 fn_; }; struct TemplateConcept : TemplateBase { template void operator()( T* t) { t->begin() ; t->end(); } }; struct Handler1 { void begin() { std::cout << "begin Handler1\n" ; } void end() { std::cout << "end Handler1\n" ; } }; class ITemplateHandler { private: typedef void (*FP1)( void* ); public: template ITemplateHandler(T& x) : p_(&x), fn_(&functions::dispatchImpl) {} void operator()() { fn_(p_); } private: template struct functions { static void dispatchImpl( void* a ) { TT* t = static_cast< TT*>(a); t->begin(); t->end(); } }; void* p_; FP1 fn_; }; template class ITemplateHandlerConcept { private: typedef void (*FP1)( void* ); public: template ITemplateHandlerConcept(T& x) : p_(&x), fn_(&functions::dispatchImpl) {} void operator()() { fn_(p_); } private: template struct functions { static void dispatchImpl( void* a ) { TT* t = static_cast< TT*>(a); CONCEPT()(t); } }; void* p_; FP1 fn_; }; struct TemplateConcept2 { template void operator()( T* t) { t->begin() ; t->end(); } }; void test() { std::cout << "TESTING TEMPLATE_PATTERN\n" ; Handler1 h1; ITemplateHandler th(h1); th(); ITemplateHandlerConcept thc(h1); thc(); TemplateBase tb1(h1); tb1(); ITemplate i(tb1); i(); i = thc; i(); } } #endif