Sometimes we need to bind the type to some data, for example, we usually use a singleton to associate a string with a function (commonly called registration), and then create an object from a string
class A {public: staticreturnnew
And then like this:
Instance::register ("A", a::create); A* a = Instance::create ("a");
Binding with strings, not very convenient, if the string is misspelled, there will be no hint at the entire compile time, and the string is no code automatically prompt, so the error rate is greatly increased, of course, you can copy/paste; If we can bind a type to data and get the relevant data by type, One is the type has the Code automatic prompt (the general spelling first several characters can complete the entire input), promptly your own spelling error, did not define this type, the compiler compiles the error.
TypeBind.h
#ifndef _type_bind_h_#define_type_bind_h_#include<assert.h>#include<map>Template<class_value>classTypebind { Public: Template<class_type>voidbind (_value Value) {M_map.insert (Std::make_pair (Typedefine<_Type>, value)); } template<class_type>_value&find () {Std::map<typedefineindifiry, _value>::iterator iter = M_map.find (typedefine<_type>); ASSERT (ITER!=m_map.end ()); returnIter->second; }Private: Template<classT>Static voidTypedefine () {} typedefvoid(*Typedefineindifiry) (); Std::map<typedefineindifiry, _value>M_map;};#endif
Test.cpp
#include"TypeBind.h"typedefvoid* (*createcallback) ();//Create a pointer to a functionclassObjectcreatefactory { Public: /** Register * @T Binding type * @callback object creation function*/Template<classT>voidRegister (Createcallback callback) {M_map.bind<T>(callback); } /** Create Object * @T Create object Type * Object created @return*/Template<classT>T*Create () {Createcallback callback= m_map.find<t>(); return(t*) callback (); } Staticobjectcreatefactory&Instance () {Staticobjectcreatefactory* factory =nullptr; if(!Factory) Factory=Newobjectcreatefactory (); return*Factory; }Private: Objectcreatefactory () {} Typebind<CreateCallback>M_map;};classA { Public: StaticA * Create () {return NewA ();}};classB { Public: Staticb* Create () {return NewB ();}};/ /register Objectcreatefactory::instance (). Register<A>( (Createcallback) a::create); Objectcreatefactory::instance (). Register<B>((createcallback) b::create);//Create a* a = Objectcreatefactory::instance (). Create<a>(); B* b = objectcreatefactory::instance (). Create<b> ();
Types of C + + templates and data binding