我正在创建我的第一个游戏。它将是吃豆人或蛇。我将使用 DirectX 11。
我现在正在写资源管理器。我想创建它最简单的使用,但我认为它设计得不好。这是我写的:
#pragma once
class Shader;
class Mesh;
class Texture;
typedef std::map<std::string, std::auto_ptr<Shader>> shaders_map;
typedef std::map<std::string, std::auto_ptr<Mesh>> meshes_map;
typedef std::map<std::string, std::auto_ptr<Texture>> textures_map;
template<class C, class E>
inline int findElementInMap(const C& cont, E *ptr)
{
C::const_iterator it = cont.begin();
int i = 0;
while(it != cont.end())
{
if(it->second.get() == ptr) // ERROR AT THIS LINE!!!!
return i;
i++;
it++;
}
return -1;
}
class ResourceManager
{
public:
ResourceManager(void);
~ResourceManager(void);
template<class T>
inline T* get(const std::string &name)
{
if(typeid(T) == typeid(Shader)) {
return (T*)getShader(name);
}
else if(typeid(T) == typeid(Mesh)) {
return (T*)getMesh(name);
}
else if(typeid(T) == typeid(Texture)) {
return (T*)getTexture(name);
}
return nullptr;
}
Shader* getShader(const std::string &name);
Mesh* getMesh(const std::string &name);
Texture* getTexture(const std::string &name);
template<class T>
inline bool add(T *ptr)
{
if(typeid(T) == typeid(Shader)) {
return addShader((Shader*)((void*)ptr));
}
else if(typeid(T) == typeid(Mesh)) {
return addMesh((Mesh*)((void*)ptr));
}
else if(typeid(T) == typeid(Texture)) {
return addTexture((Texture*)((void*)ptr));
}
return false;
}
bool addShader(Shader *ptr);
bool addMesh(Mesh *ptr);
bool addTexture(Texture *ptr);
template<class E>
inline void release(E *ptr)
{
if(typeid(E) == typeid(Shader)) {
release<shaders_map, E>(shaders, (E*)((void*)ptr));
return;
}
else if(typeid(E) == typeid(Mesh)) {
release<meshes_map, E>(meshes, (E*)((void*)ptr));
return;
}
else if(typeid(E) == typeid(Texture)) {
release<textures_map, E>(textures, ptr);
}
}
// THIS METHOD CAUSES PROBLEM
template<class C, class E>
void release(C &container, E *ptr)
{
assert(ptr != nullptr);
int index = findElementInMap<C, E>(container, ptr);
if(index < 0)
return;
C::iterator it = container.begin();
it->second.release();
}
private:
shaders_map shaders;
meshes_map meshes;
textures_map textures;
};
现在编译错误:
error C2440: '==' : cannot convert from 'Shader *' to 'Mesh *'
int findElementInMap<C,E>(const C &,E *)' being compiled
with
[
C=textures_map,
E=Shader
]
所以容器类型和元素类型不匹配。关于如何设置它的任何想法?
还是我应该从头开始构建新的资源管理器?
编辑:这就是我使用这个类的方式:
Shader *sh = new Shader();
resourceManager.add<Shader>(sh);
resourceManager.release<Shader>(sh);