Templatizing Singletons

Now, assuming we get our Singleton working just the way that we want it to, you may wish to create more Singletons in the future. You could create them all from scratch, but a better thing to do is instead create a consistent approach, creating templates and inheritance to create a single implementation that you can use for any class. At the same time, we can also learn about an alternative way of creating a Singleton class, which will look something like the following:

template <typename T> class Singleton { public:   Singleton()   {     // Set our instance variable when we are created     if (instance == nullptr)     {       instance = static_cast<T*>(this);     }     else     {       // If instance already exists, we have a problem  printf("\nError: ...

Get Game Development Patterns and Best Practices now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.