2082 8

BIT153 ยท 2082 ยท 5 marks

What are function templates? Also, write a program that swaps two values using function templates. [1+4]

What are function templates? Also, write a program that swaps two values using function templates. [1+4]

Object Oriented ProgrammingChapter 9: Templates and Generic ProgrammingFunction templates

Quick answer

A function template is a blueprint or formula for creating a family of related functions. It allows a single function definition to work with different data types, where the actual data type is determined at compile time when the function is called.

Function Templates

What are Function Templates?

Key Points:

  • Defined using the keyword template followed by template parameter list
  • Enables generic programming in C++
  • The compiler automatically generates the appropriate function for each data type used
  • Avoids code duplication for functions that perform the same operation on different types

Syntax:

template <typename T>
return_type function_name(T param1, T param2, ...) {
    // function body
}

Here, T is a type parameter (placeholder for an actual data type like int, float, char, etc.)


Program: Swapping Two Values Using Function Templates

#include <iostream>
using namespace std;

// Function template for swapping two values
template <typename T>
void swapValues(T &a, T &b) {
    T temp;
    temp = a;
    a = b;
    b = temp;
}

int main() {
    // Swapping two integers
    int x = 10, y = 20;
    cout << "Before swap (int): x = " << x << ", y = " << y << endl;
    swapValues(x, y);
    cout << "After swap  (int): x = " << x << ", y = " << y << endl;

    cout << endl;

    // Swapping two floats
    float p = 3.14, q = 7.77;
    cout << "Before swap (float): p = " << p << ", q = " << q << endl;
    swapValues(p, q);
    cout << "After swap  (float): p = " << p << ", q = " << q << endl;

    cout << endl;

    // Swapping two characters
    char c1 = 'A', c2 = 'Z';
    cout << "Before swap (char): c1 = " << c1 << ", c2 = " << c2 << endl;
    swapValues(c1, c2);
    cout << "After swap  (char): c1 = " << c1 << ", c2 = " << c2 << endl;

    return 0;
}

Output

Before swap (int): x = 10, y = 20
After swap  (int): x = 20, y = 10

Before swap (float): p = 3.14, q = 7.77
After swap  (float): p = 7.77, q = 3.14

Before swap (char): c1 = A, c2 = Z
After swap  (char): c1 = Z, c2 = A

Explanation

AspectDetail
template <typename T>Declares T as a generic type parameter
T &a, T &bPass by reference so original values are modified
T tempTemporary variable of the same generic type
Compiler behaviorGenerates separate swapValues<int>, swapValues<float>, swapValues<char> automatically

Advantage: Without templates, we would need to write three separate swap functions for int, float, and char. The function template handles all types with a single definition.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.