lundi 30 juillet 2018

C++ Singleton Instance disable re-call

When using the Meyers singleton:

class Singleton
{
public:
    static T& instance()
    {
        static T instance;
        return instance;
    }

    void Hello()
    {
        std::cout <<"Hello!\n";
    }

protected:
    Singleton() = default;
    ~Singleton() {};

private:
    Singleton(Singleton const&);
    Singleton& operator=( Singleton const& );
};

You are able to call the instance as follow:

Singleton::instance().Hello();

or

Singleton& s = Singleton::instance();
s.Hello();

But I'm wondering if there is a way to block this:

Singleton::instance().instance();

How to avoid to call instance() as a method (with the .) and only support the static call with the :: ?

Is there a way to use static_assert, template enable_if or anything else?

Aucun commentaire:

Enregistrer un commentaire