Chenna V
Chenna V

Reputation: 10493

Inheriting from a singleton template

I was looking at an opensource library VLMC and found this implementation of a singleton. The way it is done is, for creating a singleton class 'Library', Library was inherited from a Singleton. Like this

// SINGLETON_HPP

template <typename T>
class       Singleton
{
   //regular singleton implementation
    protected:
      Singleton(){}
      virtual ~Singleton(){}
};

template <typename T>
T*  Singleton<T>::m_instance = NULL;

// LIBRARY_H_

class Library : public Singleton<Library>
{
  //some other stuff 
private:
    Library();
    virtual ~Library(){}

friend class    Singleton<Library>;
}

Is this a good design? And what advantages does this design provide? Thank you.

CV

Upvotes: 2

Views: 223

Answers (1)

selalerer
selalerer

Reputation: 3924

If you need one instance of a class in some global place where everybody see it, then create one instance and put it somewhere everybody can see it. It is bad design to make the class know how many instances of it will exist and limit basic usage of the class.

I've seen more than once that a class that seemed like a singleton at the beginning of the project had few instances at the end of the project.

Upvotes: 4

Related Questions