Lesson 27 +35 XP

Generic Functions: Function Templates

Generic Functions: Function Templates

Swapping two ints, two doubles and two chars needs exactly the same steps; only the type differs. Writing three overloaded functions duplicates code.

A function template (a generic function) is written once, with the type as a parameter, and the compiler generates the version for each type used. Templates are C++'s tool for parametric polymorphism and the foundation of the STL.

1. Syntax

texttt{template} langletexttt{class} Trangle return-type function-name(arguments of type T) { dots }
  • template tells the compiler a template follows.
  • <class T> declares a template parameter T that stands for a type. The keyword typename may be used instead of class; they mean the same here.
  • T can be used wherever a type name is needed: arguments, return type, local variables.
C++
template <class T>
void swapValues(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

2. How Templates Work: Instantiation

A template is not a function: it is a recipe. When the compiler sees a call such as swapValues(x, y) with int arguments, it deduces T = int and generates (instantiates) a real function swapValues<int>.

A separate version is generated for each distinct type used. This happens at compile time, so templates cost nothing at run time, but they can increase program size (code bloat).

One template, several generated functionsOne template, several generated functions

C++
#include <iostream>
using namespace std;

template <class T>
void swapValues(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    int i1 = 10, i2 = 20;
    double d1 = 1.5, d2 = 9.25;
    char c1 = 'A', c2 = 'Z';

    swapValues(i1, i2); // swapValues<int>
    swapValues(d1, d2); // swapValues<double>
    swapValues(c1, c2); // swapValues<char>

    cout << "ints:    " << i1 << " " << i2 << endl;
    cout << "doubles: " << d1 << " " << d2 << endl;
    cout << "chars:   " << c1 << " " << c2 << endl;
    return 0;
}

Output:

OUTPUT
ints:    20 10
doubles: 9.25 1.5
chars:   Z A

3. A Generic Sort

Templates shine for algorithms. One bubble sort serves every type that supports < and assignment, including user-defined classes that overload <.

C++
#include <iostream>
using namespace std;

template <class T>
void bubbleSort(T a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (a[j + 1] < a[j]) {
                T temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}

template <class T>
void printArray(const T a[], int n) {
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}

int main() {
    int marks[5] = {72, 45, 90, 61, 88};
    double prices[4] = {9.99, 2.5, 7.25, 3.0};
    char letters[6] = {'d', 'a', 'f', 'b', 'e', 'c'};

    bubbleSort(marks, 5);
    bubbleSort(prices, 4);
    bubbleSort(letters, 6);

    printArray(marks, 5);
    printArray(prices, 4);
    printArray(letters, 6);
    return 0;
}

Output:

OUTPUT
45 61 72 88 90 
2.5 3 7.25 9.99 
a b c d e f 

4. Templates with Multiple Parameters

A template can have more than one type parameter, separated by commas.

C++
#include <iostream>
using namespace std;

template <class T1, class T2>
void display(T1 x, T2 y) {
    cout << x << " and " << y << endl;
}

template <class T1, class T2>
double average(T1 a, T2 b) {
    return (a + b) / 2.0;
}

int main() {
    display(1999, "Year");                                   // T1 = int, T2 = const char*
    display(12.34, 'X');                                     // T1 = double, T2 = char
    cout << "average(4, 7.5) = " << average(4, 7.5) << endl; // int and double
    return 0;
}

Output:

OUTPUT
1999 and Year
12.34 and X
average(4, 7.5) = 5.75

Explicitly specifying the type

With a single parameter T, largest(4, 7.5) fails: T cannot be both int and double. The type can be given explicitly in angle brackets:

C++
template <class T>
T largest(T a, T b) {
    return (a > b) ? a : b;
}

largest(4, 7.5);         // error: T deduced as int and as double
largest<double>(4, 7.5); // OK: T = double, 4 is converted

5. Overloading Function Templates

A template can be overloaded by another template or by an ordinary function. The compiler prefers, in order:

  1. an ordinary function that matches exactly;
  2. a template that can be instantiated to match exactly;
  3. an ordinary function reached through the usual conversions.

An ordinary function with the same name, written for one particular type, is called an explicit specialisation in effect: it replaces the generic version for that type. This is how special cases are handled, such as comparing C strings by content rather than by pointer.

C++
#include <iostream>
#include <cstring>
using namespace std;

template <class T>
T largest(T a, T b) { // generic version
    cout << "[template] ";
    return (a > b) ? a : b;
}

const char* largest(const char* a, const char* b) { // ordinary function: exact match wins
    cout << "[C-string version] ";
    return (strcmp(a, b) > 0) ? a : b;
}

template <class T>
T largest(T a, T b, T c) { // overloaded template: three arguments
    return largest(largest(a, b), c);
}

int main() {
    cout << largest(3, 9) << endl;
    cout << largest(2.5, 1.5) << endl;
    cout << largest("apple", "mango") << endl; // compares contents, not addresses
    cout << largest(4, 11, 7) << endl;
    return 0;
}

Output:

OUTPUT
[template] 9
[template] 2.5
[C-string version] mango
[template] [template] 11

Without the ordinary function, the template would compare the two pointers (memory addresses), not the words.

6. Non-Type Template Arguments

Besides types, a template can take constant values as parameters, such as an integer size. The value must be known at compile time.

C++
#include <iostream>
using namespace std;

template <class T, int N>
T sumArray(const T (&a)[N]) { // N is deduced from the array's size
    T total = T();
    for (int i = 0; i < N; i++) {
        total = total + a[i];
    }
    return total;
}

int main() {
    int a[4] = {1, 2, 3, 4};
    double b[3] = {0.5, 1.25, 2.0};
    cout << "sum of a = " << sumArray(a) << endl; // T = int, N = 4
    cout << "sum of b = " << sumArray(b) << endl; // T = double, N = 3
    return 0;
}

Output:

OUTPUT
sum of a = 10
sum of b = 3.75

7. Templates vs Overloading vs Macros

Function templateFunction overloadingMacro (#define)
one definition, many typesone definition per typetext substitution
same algorithm for every typeeach version can differno type checking
type-checked when instantiatedtype-checkednot type-checked
new types work automaticallyeach new type needs a new functionworks on any text, unsafely

Advantages and disadvantages of templates

AdvantagesDisadvantages
code is written and tested once (reusability)code bloat: one copy per type used
type safe, unlike macroserror messages can be long and hard to read
no run-time cost (resolved at compile time)template definitions must be visible where used (usually in headers)
basis of generic libraries such as the STLolder compilers had poor template support
💡 Tip

Key points to remember

  • template <class T> (or typename T) makes a generic function; the type is a parameter.
  • The compiler deduces T from the arguments and instantiates a version per type, at compile time.
  • Use <class T1, class T2> for several types, and f<double>(...) to state the type explicitly.
  • An ordinary function that matches exactly is preferred over a template (used for special cases).
  • Templates give parametric polymorphism; they can cause code bloat.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What is a function template? Write a generic function to swap two values and use it for int, double and char. (5 Marks)
  • Write: the syntax, instantiation, and the swapValues program with output.
  • Q2. Write a function template to sort an array using bubble sort. (5 Marks)
  • Q3. Explain function templates with multiple parameters and the overloading of template functions. (10 Marks)
  • Write: the display/average program, the three-step preference rule, and the largest program with the C-string version.
  • Q4. What are the advantages and disadvantages of templates? (2.5 Marks)
  • Q5. Differentiate between function templates and function overloading. (2.5 Marks)