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 dynamicly struct 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 something system("pause"); return 0; }