模拟标准c++中的Rtti

来源:互联网 发布:开关柜设计软件 编辑:程序博客网 时间:2024/06/06 07:11
delphi C# Java都有自己的Rtti,只有C++,它只是个标准,iso中没有定义Rtti,只是各个厂商在自己的产品库中加入了自己的Rtti,但不通用。下面的代码来自网上,简单实现了一个工厂方法。其实之前我也写过一些关于C++的Rtti。不过这篇代码思路比较好(Win7下运行有问题,没有仔细调试)。
// ConsoleDemo.cpp : 定义控制台应用程序的入口点。// #include "stdafx.h" #pragma once#include <map>#include <string> using namespace std;class DynBase;struct ClassInfo;bool Register(ClassInfo* ci);typedef DynBase* (*funCreateObject)(); //Assistant class to create object dynamiclystruct ClassInfo{public:string Type;funCreateObject Fun;ClassInfo(string type, funCreateObject fun){Type = type;Fun = fun;Register(this);}}; //The base class of dynamic created class.//If you want to create a instance of a class ,you must let//the class derive from the DynBase.class DynBase{public: static bool Register(ClassInfo* classInfo); static DynBase* CreateObject(string type); private:static std::map<string,ClassInfo*> m_classInfoMap; };  std::map< string,ClassInfo*> DynBase::m_classInfoMap = std::map< string,ClassInfo*>(); bool DynBase::Register(ClassInfo* classInfo){m_classInfoMap.insert(pair< string,ClassInfo*>(classInfo->Type,classInfo));//m_classInfoMap[classInfo->Type] = classInfo;return true;} DynBase* DynBase::CreateObject(string type){if ( m_classInfoMap[type] != NULL ){return m_classInfoMap[type]->Fun();}return NULL;} bool Register(ClassInfo* ci){return DynBase::Register(ci);}  class DerivedClass : public DynBase{public: virtual ~ DerivedClass (); DerivedClass (); static DynBase* CreateObject(){return new DerivedClass ();} private: static ClassInfo* m_cInfo;};   DerivedClass::~ DerivedClass (){// ToDo: Add your specialized code here and/or call the base class} DerivedClass:: DerivedClass (){ } ClassInfo* DerivedClass::m_cInfo = new ClassInfo("DerivedClass",(funCreateObject)( DerivedClass::CreateObject));int _tmain(int argc, _TCHAR* argv[]){DerivedClass * instance = (DerivedClass *)DynBase::CreateObject("DerivedClass");//do somethingsystem("pause");return 0; } 
原创粉丝点击