CplusplusTemplates


Templates in C++

A Template in C++ is a mold for an algorithm along with the template function that can operate on a generic datatype, which will allow you to use the same function on many different types of data. The T in template< class T > is a generic datatype.

Template class is an entire class that operates on a generic datatype. You also have to be careful what you name the generic class and regular class, Example: if you have a generic class named myGeneric and a regular class also named myGeneric, then you are going to get errors. A non-templated class organization tends to be messy because you almost never have all of the classes in the same file. Templates do not have to be based on a single generic datatype so you can have parameterized datatypes.

The compiler analyzes the datatypes that are passed into the function and creates the appropriate template based on the return value. C++ also allows you to use values of a particular datatype. Template classes with different value parameters are considered totally different types, also doubles are twice as large as ints.

A value parameter could be of a generic datatype. Templates though are limited. If you try to program templates in the way using .h and .cpp files in MSVC6, it will give you errors.
C++ goes through the template definition, copies the code, and replaces every instance of the parameterized type name with the actual type name. The compiler performs the copying for you automatically when you compile the program so that you don’t have to do it manually.

A template is nothing more than a copied-and-pasted bunch of code, the compiler does all the work for you. Therefore, you can write a really fast algorithm and have it run at full speed for every datatype you want.

For me, templates at first was a little bit confusing. But after some research and time put into it, they are becoming easier and easier.

Source:
Data Structures for Game Programmers: Ron Penton and Andre LaMothe, pp. 14-36