【问题标题】:templated singleton class - how to handle private constructor模板化单例类 - 如何处理私有构造函数
【发布时间】: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&lt;Game&gt; 成为朋友

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


【解决方案1】:

ctor Singleton() -> 受保护?

【讨论】:

    【解决方案2】:

    允许 ctor 公开将破坏单身人士的整个愿景。

    不,不是真的。 Game 应该有一个私有构造函数。 Singleton 的构造函数无关紧要。 Singleton&lt;Game&gt; 的实例不会帮助任何人获得 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&lt;Game&gt; 或至少 Singleton&lt;Game&gt;::Instance 的好友,以允许调用其构造函数。

    【讨论】:

    • 请看我的更新。我已经尝试过与Singleton&lt;Game&gt; 成为朋友并使用受保护的构造函数,但现在我遇到了编译错误。
    • 这是一个链接器错误。您需要定义构造函数,而不仅仅是声明它。最简单的方法是将空主体 {} 添加到类内部的构造函数声明中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多