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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.