我正在使用工厂模式。它基本上允许在编译时注册类并存储在映射中。然后可以使用 BaseFactory::createInstance() 返回一个实例
我不确定地图在编译时如何保存类名!如何在运行时有效的编译时分配内存?
在这种情况下,所有类都是从父类 Bump_BaseObject 派生的
//C++ STL used for adding Reflection
#include <string>
#include <map>
class Bump_BaseObject;
/**
* Derived Base objects creation factory
*/
template<typename T>
Bump_BaseObject* createT(void)
{
#pragma message("createT instantiated")
return new T();
}
struct BaseFactory {
typedef std::map<std::string, Bump_BaseObject*(*)()> map_type;
//return an instance of the class type 's'
static Bump_BaseObject* createInstance(const std::string& s) {
map_type::iterator it = getMap()->find(s);
if(it == getMap()->end())
return 0;
//this is where we instatiate and allocate memory for the object(it must NOT have any arguments)
//we could write a variant that accepts args, but there is no need.
return it->second();
}
//check if 's' is present in the map of registered types
static bool checkIfRegisteredType(const std::string& s) {
map_type::iterator it = getMap()->find(s);
if(it == getMap()->end())
return false;
return true;
}
protected:
static map_type* getMap() {
// never delete'ed. (exist until program termination)
// because we can't guarantee correct destruction order
if(!objectMap) { objectMap = new map_type; }
return objectMap;
}
private:
static map_type * objectMap;
};
#define VALUE_TO_STRING(x) #x
template<typename T>
struct DerivedRegister : BaseFactory {
DerivedRegister(const std::string& s) {
#pragma message("Type registered")
getMap()->insert(std::pair<std::string, Bump_BaseObject*(*)()>(s, &createT<T>));
}
};
还有一种方法可以在注册类名时打印它们吗?