Game Development Reference
In-Depth Information
public:
Singleton()
{
assert(m_instance == nullptr);
if (m_instance == nullptr)
{
m_instance = static_cast<T*>(this);
}
}
virtual ~Singleton()
{
m_instance = nullptr;
}
static T& GetSingleton()
{
return *m_instance;
}
static T* GetSingletonPtr()
{
return m_instance;
}
};
template <typename T>
T* Singleton<T>::m_instance = nullptr;
There are three main aspects of this class that you should pay attention to with respect to
implementing template classes. The very first line of Listing 21-1 shows that you use the template
keyword to tell the compiler that we are creating a template. Using typename T then tells the
compiler that the type T will be provided when we specialize this template in our code. The type T is
then used to create a static pointer to a T object named m_instance .
The last important piece of template code is the definition of the m_instance variable on the last line.
The template <typename T> keywords are needed again as the variable definition exists outside
of the template class block.
The Singleton constructor contains an assert to alert you if you try to create more than a single
instance of a particular object. There is also a static cast as the pointer in the constructor will be
of type Singleton , not type T . It's safe to use a static cast and not a dynamic cast in this instance
because we will only ever be casting from a Singleton to the type that derived from Singleton .
Listing 21-2 shows how we can use the Singleton template when creating another class, the
EventManager .
 
Search WWH ::




Custom Search