是否可以强制 class 仅由单例实例化

Is it possible to force a class to be instantiated by singleton-only

当我用C++11写代码的时候,我通常使用设计模式Singleton。以下是我设计单身人士的方式:

template<typename T>
class Singleton {
private:
    Singleton() = default;
    ~Singleton() = default;
public:
    static T * GetInstance() {
        static T t;
        return &t;
    }
    Singleton(const Singleton &) = delete;
    Singleton(Singleton &&) = delete;
    Singleton & operator=(const Singleton &) = delete;
    Singleton & operator=(Singleton &&) = delete;
};

然后,我们可以定义任何我们想要的class,比如class Test{};Singleton<Test>::GetInstance();会生成一个对象

一切正常。

然而,今天我认为class Test{};可以摆脱限制。我的意思是,尽管我定义了 class Singletion<T>,但其他开发人员可以定义他们的 class,例如 Test,并且不要使用 Singleton , 所以他们可以根据需要生成许多对象。但是我想要的是,如果你决定定义一个class,它应该是单例的,你不能通过调用构造函数来生成对象,而只能通过调用Singleton<Test>::GetInstance().

一句话,我想得到这个:

Test t;  // compile error
Test *p = Singleton<Test>::GetInstance(); // OK

为此,我尝试了一些棘手的方法,例如,我让 class Test 继承 Singleton<Test>:

class Test : public Singleton<Test> {
public:
    Test() : Singleton<Test>() {}
};

因此,如果您正在定义一个 class,它应该是单例,您将继承 class Singleton,现在您的 class 无法生成任何其他对象通过调用构造函数。但它不起作用,因为 Singleton 的构造函数是私有的。但是如果我在class中写friend T; SingletonTest t;就会变成合法的...

看来我不能强制class用户只能通过Singleton来构造一个对象

有人可以帮助我吗?或者告诉我我正在做一些不可能的事情...

您可以使用 CRTP 模式来实现此目的

template <class T>
class Singleton {
public:
    Singleton& operator = (const Singleton&) = delete;
    Singleton& operator = (Singleton&&)      = delete;

    static T& get_instance() {
        if(!instance)
            instance = new T_Instance;
        return *instance;
    }

protected:
    Singleton() {}

private:
    struct T_Instance : public T {
        T_Instance() : T() {}
    };

    static inline T* instance = nullptr;
};

class Example : public Singleton<Example> {
protected:
    Example() {}
};

int main()
{
    auto& test = Example::get_instance();
    Example e; // this will give you error
}