#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;
}
最简单的C++反射
最新推荐文章于 2024-06-26 16:08:10 发布