【发布时间】:2012-07-13 02:44:50
【问题描述】:
我知道这已经讨论了多少次了,但我还没有找到合适的解决方案来解决我的问题。我刚刚在我的项目中实现了一个 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>;
//...
}
但现在我有类似的东西:
对'Singleton::Singleton()'的未定义引用
在函数Game::Game() 中为空
【问题讨论】:
-
您的问题到底是什么?该游戏不能调用 Singleton
的 ctor,因为 Singleton-ctor 是私有的? -> 使 Singleton 的 ctor 受到保护。还是 Game 的 ctor 必须是公开的,这样 Singleton::instance 才能构造 Game-object?
标签: c++ templates constructor singleton private