CIS 3142 Lecture 11

CISC 3142
Programming Paradigms in C++
Templates

The Motivation — Genericity / Type-Parameterized Entities

Many groups of algorithms and classes have the same implementation with the sole exception of the type they operate on. For example the code used for searching through an array:
for (int i = 0; i < n; i++)
	if (searchVal == a[i] return true;
return false;
is the same regardles of whether the elements are integers, doubles, or strings. Similarly, one could define a Simple class that holds double's that is essentially identical to our Simple class of int values, with the exception of some type declarations. Such code is quite common.

It's therefore highly desireable to be able to write code for which certain types are left unspecified and which can be filled in as needed. As another example, we'd like to be able to write a sort without specifying the element type of the array, and then as we need it, specify in one place that we want the element type to be int, in another that we want an array of strings be sorted and so on.

This style of coding is called generic programming and it's provided by a language feature of C++ called templates

Generic Programming

Function and Class Templates

Template Overview

Function templates Class templates Where do template definitions go?

A Min Function Transformed into a Template

Once Again

A Beginner's Tip for Working with Templates

When I first began working with templates, I often found it a bit easier to code a corresponding clas with a simple type first and then transform it into a template:
Generics
C++ Java
Basic mechanism Templates Generic constraints enforced by compiler
Code bloat Each new type instantiation Single class
Typing I Static (compile-time) duck typing Compiler enforces generics, standard super/subclass rules
Typing II Any type eligible for instantiation Class types only

Code Used in this Lecture