简体   繁体   English

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

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

I have the following code ( it's on ideone.com ): 我有以下代码( 位于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;
}

I can't seem to get the initialization of s_pool outside of the class to compile. 我似乎无法在类之外进行s_pool的初始化以进行编译。 Can anyone help me figure out how to make this work? 谁能帮我弄清楚如何进行这项工作? Note I'm using C++03 only. 注意我仅使用C ++ 03。

I think that you forgot how initializing a static data member works in general: 我认为您忘记了初始化静态数据成员的一般方式:

struct Data { int i; };

struct Holder { static Data StaticMember; };

Data Holder::StaticMember = { 1 };
^    ^~~~~~~~~~~~~~~~~~~~ static member qualified name
\~~~ static member type

If you look at your declaration, it is striking that you forgot one of the two above: 如果您看一下您的声明,那令人震惊的是您忘记了上述两个之一:

// 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

Once corrected it just works 更正后即可正常工作

EDIT: I was under the impression that: 编辑:我的印象是:

You must explicitly give value to the static value for each instantiation of the template: 您必须为模板的每个实例显式地将值赋予静态值:

 CList<int>::CMemoryPool<CList<int>::Entry>::s_pool(1); 

must be somewhere in your *.C files... 必须在您的* .C文件中的某处...

Alternatively, use a static local variable in a method of the table used to get the value. 或者,在用于获取值的表的方法中使用静态局部变量。

But after playing a bit, this seems to compile in ideone 但是玩了一点之后,这似乎可以在ideone中编译

template<class T>
CMemoryPool<typename CList<T>::Entry> CList<T>::s_pool(1);

I still recommend @FredOverflow solution as it protects your from static initialization problems 我仍然推荐@FredOverflow解决方案,因为它可以保护您免受静态初始化问题的困扰

Static data members inside class templates are somewhat of a pain to initialize. 类模板中的静态数据成员很难进行初始化。 I suggest a factory function instead. 我建议改为使用工厂功能。 Then you don't need to worry about defining the variable somewhere else. 然后,您不必担心在其他地方定义变量。

Just rewrite the line 只需重写行

static CMemoryPool<Entry> s_pool;

to

static CMemoryPool<Entry>& s_pool()
{
    static CMemoryPool<Entry> foobar;
    return foobar;
}

And then use s_pool() instead s_pool everywhere. 然后在任何地方都使用s_pool()而不是s_pool You get lazy initialization as a benefit. 您会获得延迟初始化的好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM