Object-Orientation FAQ

2.8) What Are Generics And Templates?

Short Answer: Parametric Polymorphism (although various implementations
              provide various subsets).
Generics (or Templates in C++) refer to the ability to parameterize types
and functions with types.  This is useful for parameterized classes and
polymorphic functions as found in languages such as Ada, C++, Eiffel, and
etc., although these are "syntactic" or restricted forms [Cardelli 85].
Generics are orthogonal to inheritance, since types (and classes)
may be generically parameterized.  Generics provide for reusability in
programming languages.  An example is a Stack with a generically
parameterized base type.  This allows a single Stack class to provide
many instantiations such as a Stack of ints, a Stack of any fundamental
or user defined type, or even a Stack of Stacks of ...  Another example is
a polymorphic sort function taking a base type with a comparison operator.
The function can be called with any type (containing a comparison operator).
See [Booch 87b] for several examples in Ada and [Stroustrup xx] and [Murray
93] for examples in C++.
While generics have many advantages, typical limitations include a static
nature, which is an advantage for strong typechecking but a potential
disadvantage when causing dynamic compilation (leading to a time/space
efficiency tradeoff), and sources can cause inlining and create source code
dependencies and expand code size (unlike a single-body or "true"
parametrically polymorphic implementation.  Generics can also be viewed as a
special case of type variables.
Functions are typically generic in statically-typed parametrically-polymorphic
languages.  One such popular functional language is ML, in which all functions
are generic.  Russell and Haskel are more modern variants (references are
forthcoming, however see APPENDIX E).

This document was translated by ms2html v1.8 on 04.06.96.