Redirected from Template
Templates are similar to macros, in that they are interpreted by the preprocessor and don't reduce efficiency. However templates are type-safe, which encourages the writing of error free code.
Templates were left out of some C++ derived languages, such as Java and C#, because these languages have other methods of dealing with the same problems. However templates are of great utility to programmers in C++, especially when combined with multiple inheritance and operator overloading. The Standard Template Library (STL) for C++ provides many useful functions within a framework of connected templates.
There are two kinds of templates. A "class template" is often used to make a generic container. For example, the STL has a linked list container. To make a linked-list of integers, you write "list<int>". A list of strings is denoted "list<string>". A list has a set of standard functions associated with it, which work no matter what you put between the brackets.
There are also function templates. For example, the STL contains the function "max(x,y)", which returns either x or y depending on which is larger. This works whether x and y are integers, strings, or any other type for which it makes sense to say "x < y". If you have defined your own data type, you can use operator overloading to define the meaning of "<" for your type, thus allowing you to use the max function. While this may seem a minor benefit in this isolated example, in the context of a comprehensive library like the STL it allows the programmer to get extensive functionality for a new data type, just by defining a few operators for it.
Search Encyclopedia
|