【发布时间】:2021-08-02 14:37:39
【问题描述】:
我正在尝试以下...
#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;
}
【问题讨论】:
-
无法重现,我也收到 msvc 错误:godbolt.org/z/ccdEfza5q
-
你为什么重复
Singleton<ABC>::InstPtr Singleton<ABC>::ptr;两次? -
你可以看看 Meyers 的 Singleton。
-
为什么我得到未定义的引用`Singleton
::ptr' -
为什么要为一种不再被推荐的模式编写如此复杂的代码,而当一个人可以制作单例时,代码却远少于此?
标签: c++ templates definition template-specialization explicit-specialization