不多说了,直接上代码吧!
定义:
typedef CReflexBase* (*Fun_Create)() ;
class CReflexBase
{
static std::map<string, Fun_Create> stmapReflex;
public:
CReflexBase(){};
virtual ~CReflexBase(){};
static bool RegisterCreator(string name, Fun_Create func)
{
stmapReflex[name] = func;
return true;
}
static CReflexBase* Create(string name)
{
Fun_Create p = stmapReflex[name];
if(p)
{
return p();
}
else
{
return NULL;
}
}
};
std::map<string, Fun_Create> CReflexBase::stmapReflex;
#define START_REFLEX_CLASS(cls,base)\
class cls:public base\
{\
public:\
static CReflexBase* Create()\
{\
return new cls;\
}\
#define END_REFLEX_CLASS(cls)\
};\
static bool blRegister##cls=CReflexBase::RegisterCreator(#cls,cls::Create);
用法:
START_REFLEX_CLASS(CTest1, CReflexBase)
virtual void Printf()
{
cout << typeid(*this).name() << endl;
}
END_REFLEX_CLASS(CTest1)
START_REFLEX_CLASS(CTest2, CTest1)
virtual void Printf()
{
cout << typeid(*this).name() << endl;
}
END_REFLEX_CLASS(CTest2)
int _tmain(int argc, _TCHAR* argv[])
{
CReflexBase* pTest1 = CReflexBase::Create("CTest1");
CReflexBase* pTest2 = CReflexBase::Create("CTest2");
((CTest1*)pTest1)->Printf();
((CTest1*)pTest2)->Printf();
return 0;
}