最简单的C++反射

来源:互联网 发布:java中需要标识符 编辑:程序博客网 时间:2024/06/05 17:14
#include <iostream>#include <map>#include <string>using namespace std;typedef void* (*pCreateObject)();class ObjectFactory{public:    static void registerCallback(const string& name, pCreateObject);    static void* getClassByName(const string& name);private:    static map<const string, pCreateObject> m_map;};map<const string,pCreateObject> ObjectFactory::m_map;void ObjectFactory::registerCallback(const string& name, pCreateObject p){    m_map.insert(std::pair<const string, pCreateObject>(name, p));}void* ObjectFactory::getClassByName(const string& name){    map<const string, pCreateObject>::iterator        iter = m_map.find(name);    if (iter != m_map.end()){        return (*iter->second)();    }    else{        return nullptr;    }}class Lenovo{public:    void show(){        cout << "show" << endl;    }private:};#define DEFINERCALLBACK( className )                \    void* create##className(){                      \        return (void*)new className;                \    }                                                   DEFINERCALLBACK(Lenovo);#define REGISTERCALLBACK(className)                 \        ObjectFactory::registerCallback(            \#className, reinterpret_cast<pCreateObject>(create##className))int main(){    REGISTERCALLBACK(Lenovo);    Lenovo* p =(Lenovo*) ObjectFactory::getClassByName("Lenovo");    p->show();    delete p;    return 0;}
原创粉丝点击