Game Development Reference
In-Depth Information
slow and require much more memory than necessary. Instead the compiler creates specializations
of templates as and when it encounters them in your code. This process of creating specialized
templates from the generic templates is why the compiler considers vector<int> to be a different
type to vector<char> .
Note As you have seen in previous chapters, it can be a great idea to use type aliases to make it clear in
your code when a template specialization is declaring a new type.
What the template compiler does then is generate specific source code that is turned into
instructions by subsequent steps in the compiler. This has led to the ability of the template compiler
to be considered Turing complete . Being Turing complete means that the template compiler is
considered capable of carrying out all of the computation capabilities of an early computer created
by Alan Turing. In effect, the template compiler in C++ is able to do many things outside of just
making types generic.
Before we look at how templates can be used in game code in the next chapter, we need to cover
some of the basics. Listing 20-1 shows how a simple template can be created.
Listing 20-1. Creating a template Class
template <typename T>
class Template
{
private:
T* m_ptr;
public:
Template(T* ptr)
: m_ptr{ptr}
{
}
};
Listing 20-1 shows how we can tell the compiler that we would like our class to contain a member
variable that is of an unspecified type. This is achieved in the very first line with template <typename T> .
The <> syntax should be familiar from the STL chapters and is also the form we use to specify the
name for our generic type, in this case T .
Note Where Listing 20-1 uses the typename keyword, it's also possible to use the class keyword. The
class keyword was initially used to declare template types, but it was superseded by the typename
keyword to reduce the overloading on the class keyword. Some older code might still use the class
keyword for compatibility, but typename should be used in any new code.
 
 
Search WWH ::




Custom Search