模板单例类 - 如何处理私有构造函数

3

我知道这个问题已经被讨论了很多次,但是我没有找到适合我的问题的解决方案。我刚刚在我的项目中实现了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()中。


你的问题是什么?那个游戏无法调用Singleton<Game>的构造函数,因为Singleton-ctor是私有的?-> 将Singleton的构造函数设置为protected。或者是Game的构造函数必须是公共的,以便Singleton::instance可以构造Game对象? - MadScientist
2个回答

2

ctor Singleton() -> protected?


2
允许构造函数是公共的将破坏单例模式的整个构想。
不,实际上不会。Game应该拥有一个私有构造函数。Singleton的构造函数是无关紧要的。Singleton的实例不会帮助任何人获取另一个Game的实例,这才是你所感兴趣的。
无论如何,你可以声明构造函数为protected。或者,你可以保持构造函数为private并且与模板参数进行友元声明。但是在C++03中这种方式行不通。在C++11中应该可以工作。但是有一个小技巧:
template <typename T>
struct wrapper
{
    typedef T type;
};

template <typename T>
class Singleton
{
    friend class wrapper<T>::type;

更新: Game 应该与 Singleton<Game> 成为好友,或者至少与 Singleton<Game>::Instance 成为好友,以允许其构造函数被调用。

请看一下我的更新。我尝试了使用Singleton<Game>和使用受保护的构造函数,但现在我遇到了编译错误。 - Patryk
1
这是一个链接错误。你需要定义构造函数,而不仅仅是声明它。最简单的方法是在类内部构造函数声明中添加空的花括号 {} - n. m.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接