您好,登錄后才能下訂單哦!
這篇文章主要講解了“怎么利用C++實現一個反射類”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么利用C++實現一個反射類”吧!
代碼環境為VScode + CMake + GCC 8.1.0
首先,如何才能做到給我一個名字我就能拿到這個對象的這個值,也是比較難的一個地方,方法如下
#define OFFSET(className,fieldName) (size_t)&(((className*)0)->fieldName)
這個能夠得到該成員變量與該對象的偏移量,之后根據這個偏移量來獲取成員的值
首先這個反射類應該只有一個,要不然反射就會變得很混亂,這一個反射對象,那里一個反射對象。所以應該將該反射類變為一個單例。全局內只允許出現一個。單例類如下:
#pragma once #include "Singleton.h" #ifndef _SINGLETON_ #define _SINGLETON_ #include "Util.h" NAME_SPACE_START(myUtil) //單例模式 template<typename T> class Singleton{ public: static T* Instance(){ if(m_instance==nullptr){ m_instance = new T(); } return m_instance; } private: Singleton(); Singleton(const Singleton<T>&); ~Singleton(); Singleton<T>& operator=(const Singleton<T>&); private: static T* m_instance; }; template<typename T> T* Singleton<T>::m_instance=nullptr; #define SINGLETON_DECLARE(className) \ friend class Singleton<className>; \ className(){}; \ className(const className&){}; \ ~className(){}; \ className& operator=(const className&); NAME_SPACE_END() #endif //!_SINGLETON_
我在這個頭文件中寫了一個單例聲明SINGLETON_DECLARE,只要將這個聲明放到私有部分就行了,這個類就變為一個單例類了。
如何才能做到反射呢,應該在這個反射類中保存注冊表,傳入了對應的類名,返回對應的信息,然后使用基類實現對應的方法即可。代碼如下:
#pragma once #include "Util.h" #include <cstdint> #include <vadefs.h> #include <vector> #include <functional> #ifndef _REFLEX_ #define _REFLEX_ NAME_SPACE_START(myUtil) #include "Singleton.h" #include <map> #include <string> //因為編譯器不支持類模板和實現分開寫,所以放到一起了 class Field; class Reflex; class RObject{ public: RObject(){} virtual ~RObject(){} std::string _className; template<typename T> T get(const std::string& fieldName); template<typename T> void set(const std::string& fieldName, const T& fieldValue); void Call(const std::string& methodName); template<typename T,typename... Args> T Call(const std::string& methodName, Args... args); }; typedef RObject* (*construct)(void); //使用方法,使用REGISTER_REFLEX注冊,然后直接使用createClass即可 class Reflex{ SINGLETON_DECLARE(Reflex) public: void ReflexRegister(); RObject* createClass(const std::string& className); void RegisterClass(const std::string& className, construct constructMethod); void RegisterField(const std::string& className, const std::string& FieldName, const std::string& FieldType, const size_t& offset); void RegisterMethod(const std::string& className, const std::string& methodName, const uintptr_t& lpMethod); template<typename T> T getClassField(void* originPos, const std::string& className, const std::string& fieldName); template<typename T> void setClassField(void* originPos, const std::string& className, const std::string& fieldName, const T& fieldValue); uintptr_t getClassMethod(const std::string& className, const std::string& methodName); private: std::map<std::string, construct> m_classMap; std::map<std::string, std::map<std::string, Field>> m_fieldMap; std::map<std::string, std::map<std::string, uintptr_t>> m_methodMap; }; //僅僅用來在reflex中注冊使用 class RegisterClass{ public: RegisterClass(const std::string& className,construct constructMethod) { Reflex* factory = myUtil::Singleton<Reflex>::Instance(); factory->RegisterClass(className, constructMethod); } RegisterClass(const std::string& className,const std::string& fieldName,const std::string& fieldType,const size_t& offset) { Reflex* factory = myUtil::Singleton<Reflex>::Instance(); factory->RegisterField(className, fieldName, fieldType, offset); } RegisterClass(const std::string& className,const std::string& methodName,const uintptr_t& lpMethod) { Reflex* factory = myUtil::Singleton<Reflex>::Instance(); factory->RegisterMethod(className, methodName, lpMethod); } }; class Field{ private: std::string m_fieldType{""}; //std::string m_fieldName{""}; size_t m_offset{0}; public: Field(){} Field(const std::string& fieldType,const size_t& offset): m_fieldType(fieldType),m_offset(offset){} ~Field(){} inline std::string getFieldType(){return m_fieldType;} //inline std::string getFieldName(){return m_fieldName;} inline size_t getOffSet(){return m_offset;} inline void setFieldType(const std::string& type){ m_fieldType = type;} //inline void setFieldName(const std::string& name){ m_fieldName = name;} inline void setOffSet(const size_t& offset){ m_offset = offset;} }; class Method{ public: Method(){} Method(const std::string& name,const std::uintptr_t& method): methodName(name),lpMethod(method){} ~Method(){} inline void setMethodName(const std::string& name) { methodName = name;} inline void setLpMethod(const uintptr_t& lp) { lpMethod = lp;} inline std::string getMethodName(){return methodName;} inline uintptr_t getLpMethod(){return lpMethod;} private: std::string methodName{""}; std::uintptr_t lpMethod{0}; }; #define REGISTER_REFLEX(className) \ RObject* construct##className() \ { \ RObject* obj = new className(); \ obj->_className = #className; \ return obj; \ } \ RegisterClass registerClass##className(#className,construct##className); #define REGISTER_REFLEX_FIELD(className,fieldType,fieldName) \ RegisterClass registerClass##className##fieldType##fieldName(#className,#fieldName,#fieldType,OFFSET(className,fieldName)); #define REGISTER_REFLEX_METHOD(className,methodName) \ std::function<void(className)> className##methodName = &className::methodName;\ RegisterClass registerClass##className##method(#className,#methodName,(std::uintptr_t)&className##methodName); #define REGISTER_REFLEX_METHOD_ARGS(className,methodName,returnType,...) \ std::function<returnType(className,##__VA_ARGS__)> className##methodName = &className::methodName;\ RegisterClass registerClass##className##method##returnType(#className,#methodName,(std::uintptr_t)&className##methodName); template<typename T> T RObject::get(const std::string &fieldName) { Reflex* factory = myUtil::Singleton<Reflex>::Instance(); return factory->getClassField<T>(this, _className, fieldName); } template<typename T> void RObject::set(const std::string &fieldName, const T &fieldValue) { Reflex* factory = myUtil::Singleton<Reflex>::Instance(); factory->setClassField(this, _className, fieldName, fieldValue); } void RObject::Call(const std::string& methodName) { Reflex* factory = myUtil::Singleton<Reflex>::Instance(); std::uintptr_t temp = factory->getClassMethod(_className, methodName); if (temp == 0) return; typedef std::function<void(decltype(this))> class_method; class_method* method = (class_method*)temp; (*method)(this); } template<typename T,typename... Args> T RObject::Call(const std::string& methodName,Args... args) { Reflex* factory = myUtil::Singleton<Reflex>::Instance(); std::uintptr_t temp = factory->getClassMethod(_className, methodName); if(temp == 0) return T(); typedef std::function<T(decltype(this),Args...)> class_method; class_method* method = (class_method*)temp; return (*method)(this,args...); } RObject* Reflex::createClass(const std::string &className) { if(m_classMap.find(className)==m_classMap.end()) return nullptr; return m_classMap[className](); } void Reflex::RegisterClass(const std::string &className, construct constructMethod) { if(m_classMap.find(className)!=m_classMap.end()){ throw std::exception(); return; } m_classMap.insert(std::pair<std::string, construct>(className,constructMethod)); m_fieldMap[className] = std::map<std::string, Field>(); m_methodMap[className] = std::map<std::string, uintptr_t>(); } void Reflex::RegisterField(const std::string &className, const std::string &FieldName, const std::string &FieldType, const size_t &offset) { m_fieldMap[className][FieldName] = Field(FieldType,offset); } void Reflex::RegisterMethod(const std::string &className, const std::string &methodName, const uintptr_t &lpMethod) { m_methodMap[className][methodName] = lpMethod; } template<typename T> T Reflex::getClassField(void* originPos, const std::string &className, const std::string &fieldName) { if(m_fieldMap.find(className) == m_fieldMap.end()){ return T(); } if(m_fieldMap[className].find(fieldName) == m_fieldMap[className].end()){ return T(); } size_t offset = m_fieldMap[className][fieldName].getOffSet(); return *(T*)((size_t)originPos + offset); } template<typename T> void Reflex::setClassField(void* originPos, const std::string &className, const std::string &fieldName, const T &fieldValue) { if(m_fieldMap.find(className) == m_fieldMap.end()){ return; } if(m_fieldMap[className].find(fieldName) == m_fieldMap[className].end()){ return; } size_t offset = m_fieldMap[className][fieldName].getOffSet(); *(T*)((size_t)originPos + offset) = fieldValue; } uintptr_t Reflex::getClassMethod(const std::string &className, const std::string &methodName) { if(m_fieldMap.find(className) == m_fieldMap.end()){ return 0; } if(m_methodMap[className].find(methodName) == m_methodMap[className].end()){ return 0; } return m_methodMap[className][methodName]; } NAME_SPACE_END() #endif //!_REFLEX_
該反射類使用方法如下:
#include <iostream> #include <string> #include "Util.h" #include "Singleton.h" #include "Reflex.h" using namespace std; using namespace myUtil; class A:public RObject{ public: void show(){ cout<<"hello world"<<endl; } int add(int a,int b){ return a+b; } int m_age; A():m_age(10){} }; REGISTER_REFLEX(A) REGISTER_REFLEX_FIELD(A, int, m_age) REGISTER_REFLEX_METHOD(A, show) REGISTER_REFLEX_METHOD_ARGS(A, add, int,int,int) int main(){ Reflex* factory=Singleton<Reflex>::Instance(); A* a=(A*)factory->createClass("A"); cout<<a->get<int>("m_age")<<endl; a->set<int>("m_age", 30); cout << a->get<int>("m_age") << endl; a->Call("show"); int b = a->Call<int,int,int>("add",1,5); cout << b << endl; A* c=(A*)factory->createClass("A"); cout<<c->get<int>("m_age")<<endl; c->set<int>("m_age", 40); cout << c->get<int>("m_age") << endl; c->Call("show"); b = c->Call<int,int,int>("add",2,5); cout << b << endl; return 0; }
結果截圖
最后講解一下是怎么用的,見注釋
//首先要使用反射的類要繼承RObject //要使用反射的類和成員方法都要聲明為public class A:public RObject{ public: void show(){ cout<<"hello world"<<endl; } int add(int a,int b){ return a+b; } int m_age; A():m_age(10){} }; //這里在反射類中注冊A這個類,原理是把重復工作用宏展開來替代 REGISTER_REFLEX(A) //注冊類中的成員變量,一定要先注冊類再注冊成員變量,原理是將成員變量與對象的偏移量保存起來,用到的時候解引用來獲取值 REGISTER_REFLEX_FIELD(A, int, m_age) //注冊類的成員方法,此宏是聲明沒有返回值和入參的成員方法的,原理是使用function能夠調用成員函數的功能,將function的地址保存到注冊表中(轉為uintptr_t),需要時通過傳入的參數轉換回來,再調用 REGISTER_REFLEX_METHOD(A, show) //注冊類的成員方法,此宏是聲明有返回值和多參數的成員方法的,原理同上 REGISTER_REFLEX_METHOD_ARGS(A, add, int,int,int) int main(){ //在使用類時,要先獲取這個全局唯一的反射對象,使用它來創建對象 Reflex* factory=Singleton<Reflex>::Instance(); A* a=(A*)factory->createClass("A"); //為了能夠得到準確的類型值,這里使用模板來獲取 cout<<a->get<int>("m_age")<<endl; //設置同獲取 a->set<int>("m_age", 30); cout << a->get<int>("m_age") << endl; //調用無參且無返回值的成員函數時使用沒有模板的Call,反之使用有模板的Call a->Call("show"); int b = a->Call<int,int,int>("add",1,5); cout << b << endl; return 0; }
感謝各位的閱讀,以上就是“怎么利用C++實現一個反射類”的內容了,經過本文的學習后,相信大家對怎么利用C++實現一個反射類這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。