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

C++: specializing member requires template<> syntax

我正在尝试以下...

#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;

应该用于定义明确专门的 class 模板的 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

LIVE


而且,explicit specialization of a static data member喜欢

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

是声明,不是定义。

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

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

LIVE

An explicit specialization of a static data member of a template is a definition if the declaration includes an initializer; otherwise, it is a declaration. These definitions must use braces for default initialization:

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