Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C++ Programming Tutorial / Chapter 4: Templates, Exceptions & The STL
CPP ⏱ 12 min read

Templates: Function Templates and Class Templates

Writing duplicate algorithms for `int`, `float`, and `double` is tedious. Templates allow you to write generic code that works with any data type.

What is it?

Templates are blueprints for creating generic functions and classes. The compiler generates specialized machine code for each type used.

Why is it used?

Eliminates duplicate code and underpins the entire C++ Standard Template Library (vector, map, set).

Detailed Explanation

Template Types: 1. Function Templates: `template <typename T> T find_max(T a, T b)`. 2. Class Templates: `template <typename T> class Stack { ... };`. 3. Template Metaprogramming: Calculations executed at compile time with zero runtime cost.

Syntax Structure

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

Code Example

CPP Code
#include <iostream>
#include <string>

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

// Generic Class Template: Container Box
template <typename T>
class ResourceBox {
private:
    T item;
public:
    ResourceBox(T val) : item(val) {}
    
    T get_item() const { return item; }
    void print() const {
        std::cout << "Box Item: " << item << "\n";
    }
};

int main() {
    // Compiler generates int and double versions of get_larger_value automatically
    std::cout << "Max of 15 and 42:       " << get_larger_value(15, 42) << "\n";
    std::cout << "Max of 3.14 and 2.71:   " << get_larger_value(3.14, 2.71) << "\n";
    std::cout << "Max of Apple and Mango: " << get_larger_value(std::string("Apple"), std::string("Mango")) << "\n\n";
    
    // Using Class Template with different types
    ResourceBox<int> intBox(2500);
    ResourceBox<std::string> strBox("Python Certified");
    
    intBox.print();
    strBox.print();
    
    return 0;
}

Explanation of the Code

• `template <typename T>` declares `T` as a generic placeholder type. • The compiler generates separate, optimized functions for `int`, `double`, and `std::string` at compile time.

Expected Output

Max of 15 and 42: 42 Max of 3.14 and 2.71: 3.14 Max of Apple and Mango: Mango Box Item: 2500 Box Item: Python Certified

Real-World Application

The entire STL (`std::vector<T>`, `std::unique_ptr<T>`) is built on C++ templates.

Common Mistakes to Avoid

• Separating template declarations into `.h` and definitions into `.cpp` (templates must be defined in header files so the compiler can instantiate types at call sites). • Confusing `typename` and `class` inside template brackets (they are virtually interchangeable).

Quick Practice Challenge

Write a template function `swap_any<T>(T &a, T &b)` that swaps any two variables.

Key Takeaways

• Templates provide generic programming without runtime overhead. • The compiler generates separate type-specific code under the hood. • Define templates in header files.