An Introduction to C++ Templates
Generic programming has become a dominant programming paradigm in C++, particularly after
the incorporation of the Standard Template Library (STL) as part of the standard library in 1996.
Templates - the language feature that supports generic programming in C++ - was originally
conceived for supporting ‘parameterized types’ (classes parametrized by type information) in
writing container classes.
Templates are a compile time mechanism. Because of this, there is no runtime overhead
associated with using them. Also, using templates is completely type safe. Templates help to
seamlessly integrate all types and thereby let programmers write code for one (generic) type. So,
it serves as a mechanism for writing high-level reusable code, which is known as ‘generic
programming’. Like the structured, modular and object oriented programming approaches,
generic programming is another programming approach (and C++ supports all these four
programming paradigms! For this reason, C++ is referred to as a ‘multi-paradigm’ language).
Writing Reusable Code
Two primary means of providing reusable functionality in conventional object-oriented systems is
through inheritance and composition. Inheritance refers to creating subclasses or subtypes from
existing classes and composition refers to providing objects of other class types as data
members. "Parameterized types give us a third way (in addition to class inheritance and object
composition) to compose behavior in object-oriented systems. Many designs can be
implemented using any of these three techniques", observes [Gamma et al, 1994]. Templates
look at the problem of reusability in a different way - it uses type independence as the basis
rather than inheritance, polymorphism and composition.
One of the main objectives of C++ is to support writing low-level code for systems programming
in which performance is an important considerat