C ++ programming language is a powerful computer application language. It supports many programming styles. We will introduce the specific implementation steps of the C ++ reflection mechanism here today. You can get some helpful content.
In Java programming, reflection is often used to implement flexible configuration in the configuration file through the reflection mechanism. However, in C ++ programming, existing support is provided for this method step, so how can we configure the objects to be called in the configuration file?
Our idea is to determine the object instance through the object name, and map the Object Name and object instance through the hash table, then we can get the object through the object name. First, define a structure of the C ++ reflection mechanism:
- struct ClassInfo
- {
- public:
- string Type;
- funCreateObject Fun;
- ClassInfo(string type, funCreateObject fun)
- {
- Type = type;
- Fun = fun;
- Register(this);
- }
- };
Here, Register is defined as follows:
- bool Register(ClassInfo* ci);
Define a class. The header file is as follows:
- class AFX_EXT_CLASS DynBase
- {
- public:
- DynBase();
- virtual ~DynBase();
- public:
- static bool Register(ClassInfo* classInfo);
- static DynBase* CreateObject(string type);
- private:
- static std::map<string,ClassInfo*> m_classInfoMap;
- };
The cpp file is as follows:
- std::map< string,ClassInfo*> DynBase::m_classInfoMap =
std::map< string,ClassInfo*>();
- DynBase::DynBase()
- {
- }
- DynBase::~DynBase()
- {
- }
- bool DynBase::Register(ClassInfo* 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;
- }
The ing Class in the C ++ reflection mechanism can be inherited from DynBase, for example, CIndustryOperate.
The header file is as follows:
- class CIndustryOperate : public DynBase
- {
- public:
- CIndustryOperate();
- virtual ~CIndustryOperate();
- static DynBase* CreateObject(){return new CIndustryOperate();}
- private:
- static ClassInfo* m_cInfo;
- };
The cpp file is as follows:
- ClassInfo* CIndustryOperate::m_cInfo = new ClassInfo
("IndustryOperate",(funCreateObject)( CIndustryOperate::
CreateObject));
- CIndustryOperate::CIndustryOperate()
- {
- }
- CIndustryOperate::~CIndustryOperate()
- {
- }
The above is the implementation method of the C ++ reflection mechanism.