我有一个名为PooledResource
的模板类。它为我处理加载诸如纹理和声音之类的东西,并确保我在事故中多次加载相同的东西。某种类型的资源总是处于某个子目录中,我想让它更容易加载,因此我决定添加一个静态变量,以跟踪特定类型资源的根文件夹。模板类的静态变量的多重定义
template <typename T>
class PooledResource
{
public:
// ...
static const char* PathPrefix;
static ResourceTable myResourceTable;
static void load(const char* filename)
{
// Any attempt to use PathPrefix in here causes a compilation error
// All I want to do is use PathPrefix and filename to get the full
// path do a file and load it.
}
};
template <typename T>
const char* PooledResource<T>::PathPrefix = NULL;
template <typename T>
typename PooledResource<T>::ResourceTable PooledResource<T>::myResourceTable;
这个想法是,我可以使用这个typedef'd版本的各种类型。例如,在PooledTexture.hpp
我会:
typedef PooledResource<Texture> PooledTexture;
和PooledTexture.cpp
我会:
template <>
const char* PooledTexture::PathPrefix = "../assets/textures/";
这都将编译和运行很好,如果我不尝试在负载功能使用PathPrefix以上。当我用它虽然,我得到的错误是这样的:
90 || CMakeFiles/game.dir/PooledTexture.cpp.o:(.data+0x0): multiple definition of `ag::PooledResource<sf::Texture>::PathPrefix'
91 CMakeFiles/game.dir/lua/LuaFrame.cpp.o:/usr/include/c++/4.6/i686-linux-gnu/./bits/gthr-default.h|241| first defined here
我试图用简单的情况下复制本,试图追捕的问题,但其他情况下,我尝试似乎工作。我不确定我在这里做了什么不同,会导致这个错误。
这似乎已经做到了。尽管我仍然感到困惑......我没有将它放在示例中,因为它看起来并不相关,但是类中还有另一个静态变量(用于存储各种资源的哈希表)。它在类的块中以几乎相同的方式声明。我认为这应该是因为成为模板班。如果我将该部分放入cpp文件中,出于某种原因必须在标题中出现错误。是什么让他们不同? (我编辑了我的问题以显示其他变量) – Alex 2012-01-31 05:51:44
(哦,它的价值,我没有命名目标文件,这正是CMake自己命名的) – Alex 2012-01-31 05:52:02
@Alex你没有给出' ResourceTable'两个不同的值。 – Borealid 2012-01-31 05:56:27