我知道这个问题已经被讨论了很多次,但是我没有找到适合我的问题的解决方案。我刚刚在我的项目中实现了Meyer的单例模式类,但我想将其制作成一个模板,以便我可以像这样使用它:
class Game : public Singleton<Game>
{ /* stuff */
}
我的类定义如下:
template <typename T>
class Singleton
{
public:
static T& Instance();
private:
Singleton();
//declare them to prevent copies
Singleton(Singleton const&);
void operator=(Singleton const&);
};// END OF CLASS DEFINITION
// METHODS' DEFINITIONS
template<typename T>
T& Singleton<T>::Instance()
{
static T _instance;
return _instance;
}
将ctor设为public
会破坏单例的整个设计思路。
编辑
好的,所以我已经更新了我的Game
类并将Singleton<Game>
作为友元类。
class Game : public Singleton<Game>
{
friend class Singleton<Game>;
//...
}
但是现在我遇到了类似这样的问题:
undefined reference to 'Singleton< Game >::Singleton()'
该错误出现在空函数Game::Game()
中。