如何在模板类中初始化这个静态类变量?

How do I initialize this static class variable in my template class?

本文关键字:静态 静态类 类变量 初始化      更新时间:2023-10-16

我有以下代码(它在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。您可以获得延迟初始化。