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

生活

模板的静态数据成员的显式专门化是如果声明包含初始化式,则定义;否则,它是一个声明。这些定义必须使用大括号表示default初始化:

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

最新更新