Game Development Reference
In-Depth Information
Chapter 21
Practical Template Programming
This chapter introduces you to some practical template examples so you can see how they can be
deployed in your game development projects. You'll see how to implement a Singleton class that
will allow you to create objects that can be accessed from anywhere in your code base. The Singleton
pattern also ensures that you can only create a single instance of those classes.
You'll then see how you can create an event broadcasting system. This system itself will not use
templates, but we will be creating some friend functions that will be implemented using templates
to ensure that the objects being passed as parameters are set up to listen for events. The event
manager class will also use a template function that will calculate hash values to uniquely identify
the events in our system. Both of these example template functions will be showing you template
metaprogramming in action.
This chapter starts with the Singleton pattern.
Creating Singleton Classes with Templates
A Singleton class is used to create a single instance of an object in your program. This object
uses a static member variable and static functions to allow your code to access the object without
requiring you to pass it through all of your code. There are multiple methods you can use to implement
singletons. One common approach is to add a static member and functions to classes manually. This
approach is error prone if you create enough singletons, so it would be better to find a more consistent
approach. It turns out that we can use a template and inheritance to create a single implementation
that we can add to any class. Listing 21-1 shows the source code required to create a Singleton .
Listing 21-1. The Singleton Class
template <typename T>
class Singleton
{
private:
static T* m_instance;
205
 
Search WWH ::




Custom Search