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;
}