C, C++, MFC  

Chapter 14: Templates and Generic Programming in C++

Previous chapter: Chapter 13: Operator Overloading and Friend Functions in C++

Templates are the foundation of Generic Programming in C++. They allow you to write functions or classes that operate on data of any type without having to write separate code for int, double, or custom classes.

1. The Need for Generic Code

Imagine you need a function to swap the values of two variables. Without templates, you'd have to write three separate functions:

void swap_int(int& a, int& b);
void swap_double(double& a, double& b);
void swap_string(std::string& a, std::string& b);

Templates solve this by allowing you to define the function or class logic once, using a type parameter that the compiler fills in later.

2. Function Templates

A function template is defined using the template keyword, followed by a list of type parameters enclosed in angle brackets (<>). The type parameter is a placeholder that is often prefixed with typename or class (they are functionally identical in this context).

// T is a placeholder type (template parameter)
template <typename T>
void swap_values(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

int main() {
    int i1 = 10, i2 = 20;
    swap_values(i1, i2); // Compiler deduces T is 'int'

    double d1 = 3.14, d2 = 6.28;
    swap_values(d1, d2); // Compiler deduces T is 'double'
    return 0;
}

3. Class Templates

Class templates allow you to define generic data structures. The most famous example is the std::vector (Chapter 15), which can hold elements of any type.

// T is the generic type of the element the Pair will hold
template <typename T>
class Pair {
private:
    T first;
    T second;

public:
    Pair(T a, T b) : first(a), second(b) {}
    T get_first() const { return first; }
    // ...
};

int main() {
    // Explicitly specify the type parameter when creating an object
    Pair<int> int_pair(1, 2);
    Pair<std::string> string_pair("Hello", "World");
    
    std::cout << int_pair.get_first() << std::endl;
    return 0;
}

4. Template Instantiation

When the compiler encounters a template call (e.g., swap_values(i1, i2)), it generates a concrete function or class definition tailored to that specific type (int). This process is called template instantiation. All modern C++ features, including the entire Standard Template Library, rely heavily on templates.