如何在模板类中初始化这个静态类变量?
How do I initialize this static class variable in my template class?
我有以下代码(它在ideone.com上):
template<class T>
class CMemoryPool
{
public:
CMemoryPool(int param1)
: stuff(param1)
{}
private:
T stuff;
};
template<class T>
class CList
{
public:
struct Entry
{
T data;
};
static CMemoryPool<Entry> s_pool;
};
template<class T>
CList<T>::CMemoryPool<CList<T>::Entry>::s_pool(1);
int main()
{
CList<int> list;
}
我似乎无法在类之外获得s_pool
的初始化来编译。谁能帮我弄清楚如何使它工作?
我想你忘记了初始化静态数据成员的一般工作方式:
struct Data { int i; };
struct Holder { static Data StaticMember; };
Data Holder::StaticMember = { 1 };
^ ^~~~~~~~~~~~~~~~~~~~ static member qualified name
~~~ static member type
如果你看一下你的声明,你会惊讶地发现你忘记了上面两个中的一个:
// Only a single element: there should be a type and a name
template<class T>
CList<T>::template CMemoryPool<typename CList<T>::Entry>::s_pool(1);
// Two elements
template<class T>
CMemoryPool<typename CList<T>::Entry> CList<T>::s_pool(1);
^ ^~~~~~~~~~~~~~~~ name
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ type
一旦修正,它就会正常工作
编辑:我的印象是:
你必须为每个模板实例化的静态值显式地赋值:
CList<int>::CMemoryPool<CList<int>::Entry>::s_pool(1);
必须在*.C文件中的某个地方…
或者,在用于获取值的表的方法中使用静态局部变量。
但是在玩了一会儿之后,这似乎可以在ideone
中编译template<class T>
CMemoryPool<typename CList<T>::Entry> CList<T>::s_pool(1);
我仍然推荐@FredOverflow解决方案,因为它可以保护您免受静态初始化问题
类模板中的静态数据成员初始化起来有点麻烦。我建议使用工厂功能。这样,您就不必担心在其他地方定义变量了。
重写
static CMemoryPool<Entry> s_pool;
static CMemoryPool<Entry>& s_pool()
{
static CMemoryPool<Entry> foobar;
return foobar;
}
然后处处用s_pool()
代替s_pool
。您可以获得延迟初始化。
相关文章:
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 我的编译器是否忽略了我未使用的静态thread_local类成员
- 静态存储类C++计数
- 内联初始化的静态 const 类成员的初始化顺序保证
- 继承:动态派生类成员与静态派生类成员
- 避免在静态常量类上定义但不使用
- 根据模板参数可以选择静态的类成员
- 为什么不允许静态成员变量的初始化在类中,而允许静态静态成员的初始化
- 子类中具有不同值的静态基类属性
- 等效于 Java 静态对象类C++
- 是否可以按模板类型更改静态 const 类成员的值
- 如何在标题和CPP之间拆分静态/模板类
- 静态模板类成员函数的这两个调用之间有什么区别?
- 对静态重载(类)函数/方法的调用是不明确的
- 具有静态模板类成员的模板类:如何定义静态成员
- pthread没有静态的类
- 单例文件静态与类私有静态
- 使用折叠表达式初始化静态 constexpr 类数据成员不编译
- constexpr静态结构类成员的声明冲突
- 初始化在 C++ 中自定义类的构造函数中没有参数的静态 const 类成员