C++:专门的成员需要模板<>语法

我正在尝试以下...

#include <iostream>

using namespace std;

template<class T>
class Singleton
{
private:
    class InstPtr
    {
    public:
        InstPtr() : m_ptr(0) {}
        ~InstPtr() { delete m_ptr; }
        T* get() { return m_ptr; }
        void set(T* p)
        {
            if (p != 0)
            {
                delete m_ptr;
                m_ptr = p;
            }
        }
    private:
        T* m_ptr;
    };

    static InstPtr ptr;
    Singleton();
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);

public:
    static T* instance()
    {
        if (ptr.get() == 0)
        {
            ptr.set(new T());
        }
        return ptr.get();
    }
};

class ABC
{
public:
    ABC() {}
    void print(void) { cout << "Hello World" << endl; }
};

当我尝试在 Visual Studio 中执行以下操作时,它工作正常..但是当我使用 g++ 编译时,它失败了specializing member ‘Singleton<ABC>::ptr’ requires ‘template<>’ syntax。我在这里缺少什么?

#define ABCD (*(Singleton<ABC>::instance()))
template<> Singleton<ABC>::InstPtr Singleton<ABC>::ptr;
Singleton<ABC>::InstPtr Singleton<ABC>::ptr;

int main(void)
{
    ABCD.print();
    return 0;
}

回答

Singleton<ABC>::InstPtr Singleton<ABC>::ptr;

应该用于定义static显式专用类模板的成员,例如

template<class T>
class Singleton
{
    ...
};

// explicit specialization
template<>
class Singleton<ABC>
{
private:
    class InstPtr
    {
        ...
    };

    static InstPtr ptr;
    
    ...
};

Singleton<ABC>::InstPtr Singleton<ABC>::ptr; // definition of the static member

居住


并且,像这样的static数据成员的显式特化

template<> Singleton<ABC>::InstPtr Singleton<ABC>::ptr;

是声明,但不是定义。

您需要为其指定初始化程序,例如

template<> Singleton<ABC>::InstPtr Singleton<ABC>::ptr{}; // definition of the static member

居住

如果声明包含初始化程序,则模板的静态数据成员的显式特化是定义;否则,它是一个声明。这些定义必须使用大括号进行默认初始化:

template<> X Q<int>::x; // declaration of a static member
template<> X Q<int>::x (); // error: function declaration
template<> X Q<int>::x {}; // definition of a default-initialized static member

以上是C++:专门的成员需要模板&lt;&gt;语法的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>