模板化类的静态变量的多个定义
Multiple definitions of a static variable of a templated class
我有一个名为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
我试着用一个更简单的案例来重现这一点,试图找出问题所在,但我尝试的其他案例似乎奏效了。我不确定我在这里做了什么不同的事情会导致这个错误。
这里的问题是,变量的空间分配在标头中,然后由多个编译单元LuaFrame.cpp.o
和PooledTexture.cpp.o
包含。附带说明:将对象文件命名为.cpp.o
是令人困惑的。
因此,有两个变量具有相同的名称。
您需要将实际的空间分配(不是声明,而是分配它的位)移动到cpp
文件中,而不是头文件中,然后与应用程序的其余部分一起构建该文件。是的,您现在已经将它放在了标头中:您将其设置为NULL
的位!
EDIT:当你这样做时,头将不再有足够的信息来创建模板的实例,所以你必须为你希望使用它的每种类型显式实例化类。
相关文章:
- 在头文件中定义变量不会出错
- 如何使用 SFINAE 在方法调用中有条件地定义变量?
- 在命名空间中定义变量
- 是否可以在C++中基于程序集输出(.dll或.exe)定义变量
- 用不同类型重新定义变量
- 具有全局定义变量的递归比没有全局定义变量的递归函数获得更多的堆栈.为什么?(跳入C++)
- 定义变量类型
- 在命名空间中定义变量,但在测试中获取空值
- cmake没有定义变量
- C 中的继承:在亲子类中定义变量
- 在同一函数中定义变量及其静态等效项
- 如何在 Tensorflow C++ 中定义变量的自定义有状态 Op 保存值
- 如何将 int 和 int* 传递到函数中以定义变量
- 在定义变量时调用类函数
- 定义变量与模板
- 定义变量类型
- 为什么您可以在 switch 语句中的"默认"下定义变量,而不能在"case"下定义变量
- C 如何基于另一个变量和某些算术定义变量的值
- C 可以指向具有定义变量的函数
- C 定义变量设置值