lundi 4 septembre 2017

How to access derived constructor in Meyers singleton pattern

My code:

template<class T>
class Singleton {
public:
    static T& instance() {
        static T obj;
        return obj;
    }

protected:
    Singleton() { }
    Singleton(Singleton const& other);
    void operator=(Singleton const& other);
};

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

void test() {
    Derived::instance();
}

I'm getting this error at the static T obj line:

‘Derived::Derived()’ is protected  
     Derived() { }
     ^

How do I fix this? Maybe using the friend keyword? But that'd be a bit awkward.

Note: The reason I'm aware of the name and idea of the Meyers singleton, but am implementing it by myself, is that I can't find where I first read about it. I thought it was either in "Effective C++" or in "More Effective C++", but I can't find it there. And the examples I find on the net don't use the CRTP-generalization.

Aucun commentaire:

Enregistrer un commentaire