Encyclopedia > Templates (programming)

  Article Content

Templates (programming)

In computer programming, templates allow code to be written without consideration of the data-type with which it will eventually be used. They are a feature of C++, Ada and some other languages.

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.

All Wikipedia text is available under the terms of the GNU Free Documentation License

  Search Encyclopedia

Search over one million articles, find something about almost anything!
  Featured Article
Museums in England

... Darling Museum, Bamburgh Northumberland Fusiliers Museum[?] in Alnwick Castle Oxford Ashmolean Museum Pitt Rivers Museum[?] Staffordshire Brindley Water ...

This page was created in 30.8 ms