Comp 2673, Spring 2002
May 13, lecture notes
Reading Assignment: Chapter 12.1-12.4 Function templates - the purpose Imagine writing a function to sort an array of integers. You'll have an algorithm for reordering the list (such as bubble sort, or quicksort), and some line (or lines) of code will compare two integers to see if they're in the correct order. Now imagine writing a function to sort an array of dates. The entire block of code is the same, except for the line (or lines) that compare two dates to see if they're in the correct order. What a drag to have two functions that are so very similar - we are duplicating a lot of code. The solution to this problem is function templates, which allow us to create a range of related functions all at once. A function template is a blueprint for a function, allowing for software re-use. Function templates are an extension of overloaded function. If you want to make overloaded functions that do EXACTLY the same thing, just on different variable types, then function templates are the way to go. Example - function that prints the contents of an array The first line: template <class T> says that this function is actually a function template, with a parameters of varying type that we'll call T. "class T" means that the caller can use this function with any user-defined or built-in type. We'll call this function with three different built-in types, then a user-defined type. The compiler automatically generates 4 overloaded functions for us. functemp.cpp