Templates share source code among structurally similar families of classes and functions. Many data structures and algorithms can be defined independently of the type of data they manipulate. A template allows the separation of the type-dependent part from the type-independent part. The result is a significant amount of code sharing. A template is like a cookie cutter: all the cookies it creates have the same basic shape, though they might be made from different kinds of dough. A class template describes how to build classes that implement the same data structure and algorithm, and a function template describes how to build functions that implement the same algorithm. In other languages, these facilities are sometimes called parameterized types or genericity. Prior to templates, macros were used as a means of implementing generics. But the results were so poor that templates have superceded them. |