Sams Teach Yourself C++ in 21 Days

(singke) #1
Templates 661

19


class so that you fully understand how templates work. In a commercial program, how-
ever, you would almost certainly use the STL classes for this purpose rather than creating
your own. On the other hand, you will want to create templates for your own applica-
tions and leverage this powerful capability.
Instantiationis the act of creating a specific type from a template. The individual classes
are called instances of the template.

Instances of a template are distinct from instances of objects created using
the template. Most commonly, “instantiation” is used to refer to creating an
instance (object) from a class. Be certain to be clear about the context when
using or reading the word “instantiation.”

NOTE


Parameterized templatesprovide you with the ability to create a general class and pass
types as parameters to that class to build specific instances.
Before you can instantiate a template, however, you need to define one.

Building a Template Definition ..........................................................................


You begin the basic declaration of a template using the templatekeyword followed by a
parameter for the type. The format of this is:
template <class T>
In this case,templateand classare keywords that you use. Tis a placeholder—like a
variable name. As such, it can be any name you desire; however, either Tor Typeis gen-
erally used. The value of Twill be a data type.
Because the keyword classcan be confusing when used in this context, you can alterna-
tively use the keyword typename:
template <typename T>
In today’s lesson, you will see the keyword classused because it is what you will see
more often in programs that have already been created. The keyword typename,however,
is clearer at indicating what you are defining when the parameter is a primitive type
rather than a class.
Going back to the example of creating your own array list, you can use the template
statement to declare a parameterized type for the Arrayclass—you can use this to create
a template for an array as shown here:
Free download pdf