Unit VI - Templates & Exception Handling in C++

Topic 1: Templates

Theoretical Explanation

Templates allow generic programming in C++, enabling functions and classes to work with any data type. They promote code reusability by defining generic types that are specified at compile-time.

Example Program: Class and Function Templates

This program demonstrates a class template Box and a function template maximum to handle different data types.

#include <iostream>
#include <string>
using namespace std;

// Function template
template <typename T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}

// Class template
template <typename T>
class Box {
private:
    T item;

public:
    Box(T i) : item(i) {}

    // Member function template (implicitly templated)
    T getItem() const {
        return item;
    }

    // Member function to compare with another Box
    bool isLarger(const Box<T>& other) const {
        return item > other.item;
    }
};

int main() {
    // Using function template
    cout << "Maximum of 5 and 3: " << maximum(5, 3) << endl;
    cout << "Maximum of 2.5 and 4.7: " << maximum(2.5, 4.7) << endl;

    // Using class template
    Box<int> intBox(10);
    Box<int> anotherIntBox(5);
    cout << "Int Box Item: " << intBox.getItem() << endl;
    cout << "Is intBox larger than anotherIntBox? " << (intBox.isLarger(anotherIntBox) ? "Yes" : "No") << endl;

    Box<string> strBox("Apple");
    Box<string> anotherStrBox("Banana");
    cout << "String Box Item: " << strBox.getItem() << endl;
    cout << "Is strBox larger than anotherStrBox? " << (strBox.isLarger(anotherStrBox) ? "Yes" : "No") << endl;

    return 0;
}

Explanation:

Topic 2: Overloading Function Templates

Theoretical Explanation

Overloading function templates involves defining multiple template functions with the same name but different parameter lists or providing a specialized version for specific types. This allows tailored behavior for certain data types while maintaining generic functionality.