Notes

๐Ÿง  Understanding C++ Templates โ€“ Core Concept of the STL

๐ŸŽฏ Objective of this Lesson

In this lesson, we will cover:

  • What are C++ Templates

  • The difference between template functions and template classes

  • Why and when to use templates

  • Real-world analogy and practical code examples

  • How templates help us write generic, reusable, and maintainable code


๐Ÿ“ฆ What Are Templates in C++?

Templates in C++ are a tool for generic programming that allow you to write code that works with any data type. Instead of duplicating code for each type (e.g., int, float, double), templates allow you to write it once and reuse it for all types.

๐Ÿ” Problem Without Templates

Letโ€™s say you want to write a function that adds two numbers:

int addInt(int a, int b) {
    return a + b;
}
 
float addFloat(float a, float b) {
    return a + b;
}

You now have two nearly identical functions just because of different data types. Imagine writing this for double, long, short, etc. โ€” this quickly becomes unmanageable.


โœจ Template Functions: Writing Generic Functions

Think of templates as a magical cookie cutter. Normally, to cut cookies in different shapes (heart, star, circle), youโ€™d need multiple cutters. But what if you had one cutter that could change shape on demand? Thatโ€™s exactly what templates do โ€” adapt your code for different data types automatically.

โœ… Syntax of a Template Function:

template <typename T>
T add(T a, T b) {
    return a + b;
}
  • template <typename T> tells the compiler youโ€™re using a generic type called T.

  • T is a placeholder that gets replaced with the actual data type (int, float, double, etc.) when the function is called.

๐Ÿงช Example:

cout << add(5, 7);         // Uses T = int
cout << add(5.4, 7.6);     // Uses T = double

โœ… Output:

12
13

๐Ÿง  Note: The compiler creates a new version of the function for each distinct type used.


๐Ÿงช Letโ€™s Practice: More Template Functions

โž• Add

template <typename T>
T add(T a, T b) {
    return a + b;
}

โž– Subtract

template <typename T>
T subtract(T a, T b) {
    return a - b;
}

โœ–๏ธ Multiply

template <typename T>
T multiply(T a, T b) {
    return a * b;
}

โž— Divide (with Zero Check)

template <typename T>
T divide(T a, T b) {
    if (b == 0) {
        cout << "Error: Division by zero\n";
        return 0;
    }
    return a / b;
}

๐Ÿ’ก You now have one set of functions that can work with any number type. This is what makes templates so powerful!


๐Ÿงฑ Template Classes: Creating Generic Data Structures

๐Ÿ“ฆ What Are Template Classes?

Just like functions, classes can also be written generically using templates. A template class can hold and work with any data type.

โœ… Syntax:

template <typename T>
class Box {
public:
    T value;
    void setValue(T val) { value = val; }
    T getValue() { return value; }
};

๐Ÿง  Why Use Template Classes?

  • Write once, use with any type (e.g., int, float, string)

  • Useful in data structures: vector<T>, stack<T>, map<K, V> etc.

  • Form the backbone of STL containers!


๐Ÿงฎ Practical Example: Template Calculator Class

๐Ÿงพ Code:

template <typename T>
class Calculator {
public:
    T add(T a, T b) { return a + b; }
    T subtract(T a, T b) { return a - b; }
    T multiply(T a, T b) { return a * b; }
    T divide(T a, T b) {
        if (b == 0) {
            cout << "Error: Division by zero\n";
            return 0;
        }
        return a / b;
    }
};

๐Ÿงช Usage:

Calculator<int> intCalc;
cout << intCalc.add(5, 8);        // Output: 13
cout << intCalc.divide(10, 2);    // Output: 5
 
Calculator<float> floatCalc;
cout << floatCalc.add(5.2, 7.84); // Output: 13.04
cout << floatCalc.divide(10, 0);  // Output: Error

๐ŸŽฏ Benefits of Using Templates

BenefitExplanation
โœ… Code ReusabilityWrite once, use for any data type
โœ… Less DuplicationNo need to rewrite for each type
โœ… Type SafetyCompiler ensures correct types at compile time
โœ… STL FoundationTemplates power containers like vector, map, set
โœ… Generic AlgorithmsSort, find, search โ€” all work with any container using templates

๐Ÿ“š Summary

ConceptDescription
Template FunctionGeneric function that works with any type
Template ClassGeneric class that can store or process any type
typename T / class TDeclares a generic type placeholder
Real Use CaseSTL containers (vector<T>, map<K, V>, etc.)
BenefitDRY code, cleaner syntax, high flexibility

๐Ÿ“ Practice Challenge

Write a template function and class for the following:

  • A function maxValue(T a, T b) that returns the larger of two values.

  • A template class Storage<T> that holds a value and prints it.

Example:

template <typename T>
T maxValue(T a, T b) {
    return (a > b) ? a : b;
}
 
template <typename T>
class Storage {
    T value;
public:
    Storage(T val) : value(val) {}
    void print() { cout << "Stored: " << value << endl; }
};

References