![](/img/trans.png)
[英]How can I Declare/define/initialize a static member variable of template classes as static member variables of a class?
[英]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
的初始化以进行编译。 谁能帮我弄清楚如何进行这项工作? 注意我仅使用C ++ 03。
我认为您忘记了初始化静态数据成员的一般方式:
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
。 您会获得延迟初始化的好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.