C++ Templates

A template is a special type of class definition in the C++ language.  Normally, in C++, when a programmer creates a new type of data structure in the form of a class, the programmer can write code to declare a new variable of that new type.  For example, the following C++ code declares a new data type called “EmployeeType”:

Code Snippet

  1. class EmployeeType
  2. {
  3.     public:
  4.         EmployeeType(void);
  5.         ~EmployeeType(void);
  6.         char * FirstName;
  7.         char * LastName;
  8.         double salary;
  9. };

Without templates, to be able to use this type in a complex data structure, such as a list, queue, or stack, you’d have to create your own class and write all of the functionality to add and remove items.  If you wanted the same functionality for a type other than EmployeeType, you’d have to rewrite it all again.

A class is essentially a blueprint for an object.  A template is a a blueprint for a class.  For example, the following is a custom template:

Code Snippet

  1. template <class T> class PrintableTemplate
  2. {
  3.     public:
  4.         int GetSize();
  5. };

You can’t declare a variable of type PrintableTemplate, but you can declare a new class or type based on this template, like so:

Code Snippet

  1.     PrintableTemplate PrintableEmployee;

This line of code does two things:

  1. Causes the compiler to generate a new class based on EmployeeType, but adds the GetSize() method.
  2. Instantiates a variable of this new type.

Don’t confuse this new type with a new class that’s derived from EmployeeType.  This is a whole new class.  Note that you can now call methods directly on this type that came from the template:

Code Snippet

  1.     PrintableTemplate PrintableEmployee;
  2.     PrintableEmployee.GetSize();

In the early days of C++ templates, there were no standard templates available, so if you wanted to have a list, queue, or stack based on one of your own, custom types, you’d have to write the whole template yourself.  A couple years after templates were introduced to C++, the ANSI committee approved of a standard template library (STL) that provided the majority of templates that you’d need.  Since then, there are few times when you need to write your own templates, but you still can, of course.

That’s the short description of C++ templates.

C# is modeled somewhat on the C++ language and as of C# 2.0 (2005), the C# language has supported templates (as well as the .NET runtime itself).  In C# though, they’re called “generics” rather than “templates”, but they are virtually identical in capabilities and the syntax is very very similar as well.

Leave a Reply