C++ Programming

Templates (Generic Programming)

Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.

On this page

Templates (Generic Programming)

Templates are one of C++'s most powerful features, enabling generic programming - writing code that works with any data type. They're the foundation of the STL and modern C++.

What are Templates?

Templates allow you to write code that works with different data types without rewriting it for each type. Think of templates as "blueprints" for generating code.

Benefits:

  • Code Reusability: Write once, use with any type
  • Type Safety: Compile-time type checking
  • Performance: No runtime overhead (code generated at compile time)
  • Flexibility: Works with user-defined types

Function Templates

Function templates allow functions to work with different types.

Basic Function Template

Syntax:

1template <typename T>
2return_type function_name(T parameter) {
3    // function body
4}

Example:

1template <typename T>
2T maximum(T a, T b) {
3    return (a > b) ? a : b;
4}
5 
6int main() {
7    cout << maximum(10, 20) << endl;        // int
8    cout << maximum(3.5, 2.1) << endl;      // double
9    cout << maximum('a', 'z') << endl;      // char
10    return 0;
11}

Multiple Template Parameters

1template <typename T, typename U>
2void printPair(T first, U second) {
3    cout << first << ", " << second << endl;
4}
5 
6int main() {
7    printPair(10, "Hello");      // int, string
8    printPair(3.14, 'A');        // double, char
9    return 0;
10}

Sample Output

,

Template Type Deduction

Compiler automatically deduces types:

1template <typename T>
2void display(T value) {
3    cout << value << endl;
4}
5 
6display(10);      // T = int
7display(3.14);    // T = double
8display("Hello"); // T = const char*

Explicit Template Arguments

Specify types explicitly:

1template <typename T>
2T add(T a, T b) {
3    return a + b;
4}
5 
6int result = add<int>(5, 3);        // Explicit
7double result2 = add<double>(5.5, 3.2);

Class Templates

Class templates allow classes to work with different types.

Basic Class Template

Syntax:

1template <typename T>
2class ClassName {
3    // class members
4};

Example:

1template <typename T>
2class Stack {
3private:
4    vector<T> elements;
5    
6public:
7    void push(const T& element) {
8        elements.push_back(element);
9    }
10    
11    void pop() {
12        if (!elements.empty()) {
13            elements.pop_back();
14        }
15    }
16    
17    T top() const {
18        return elements.back();
19    }
20    
21    bool empty() const {
22        return elements.empty();
23    }
24};
25 
26int main() {
27    Stack<int> intStack;
28    intStack.push(10);
29    intStack.push(20);
30    
31    Stack<string> stringStack;
32    stringStack.push("Hello");
33    stringStack.push("World");
34    
35    return 0;
36}

Template Member Functions

Member functions defined outside class:

1template <typename T>
2class Vector {
3private:
4    T x, y;
5    
6public:
7    Vector(T x, T y);
8    T getX() const;
9    T getY() const;
10};
11 
12// Definition outside class
13template <typename T>
14Vector<T>::Vector(T x, T y) : x(x), y(y) {}
15 
16template <typename T>
17T Vector<T>::getX() const {
18    return x;
19}

Template Specialization

Provide specific implementation for particular types.

Function Template Specialization

1template <typename T>
2void print(T value) {
3    cout << "Generic: " << value << endl;
4}
5 
6// Specialization for strings
7template <>
8void print<string>(string value) {
9    cout << "String: " << value << endl;
10}
11 
12int main() {
13    print(10);           // Generic
14    print(3.14);         // Generic
15    print(string("Hi")); // String specialization
16    return 0;
17}

Sample Output

Generic: 
String:

Class Template Specialization

1template <typename T>
2class Container {
3public:
4    void display() {
5        cout << "Generic container" << endl;
6    }
7};
8 
9// Specialization for int
10template <>
11class Container<int> {
12public:
13    void display() {
14        cout << "Integer container" << endl;
15    }
16};

Sample Output

Generic container
Integer container

Template Parameters

Non-Type Template Parameters

Templates can take values, not just types:

1template <typename T, int N>
2class Array {
3private:
4    T data[N];
5    
6public:
7    T& operator[](int index) {
8        return data[index];
9    }
10    
11    int size() const {
12        return N;
13    }
14};
15 
16int main() {
17    Array<int, 5> arr;  // Array of 5 integers
18    Array<double, 10> arr2;  // Array of 10 doubles
19    return 0;
20}

Default Template Parameters

1template <typename T = int, int N = 10>
2class Buffer {
3    T data[N];
4};
5 
6int main() {
7    Buffer<> buffer1;        // Uses defaults: int, 10
8    Buffer<double> buffer2;  // double, 10
9    Buffer<int, 20> buffer3; // int, 20
10    return 0;
11}

Template Constraints (C++20)

Concepts (C++20) allow constraining template parameters:

1template <typename T>
2concept Addable = requires(T a, T b) {
3    a + b;
4};
5 
6template <Addable T>
7T add(T a, T b) {
8    return a + b;
9}

Variadic Templates (C++11)

Templates that accept variable number of arguments:

1template <typename... Args>
2void print(Args... args) {
3    ((cout << args << " "), ...);  // C++17 fold expression
4}
5 
6int main() {
7    print(1, 2.5, "Hello", 'A');  // Works with any number of args
8    return 0;
9}

Common Template Patterns

Pattern 1: Generic Swap

1template <typename T>
2void swap(T& a, T& b) {
3    T temp = a;
4    a = b;
5    b = temp;
6}

Pattern 2: Generic Find

1template <typename Iterator, typename T>
2Iterator find(Iterator first, Iterator last, const T& value) {
3    for (Iterator it = first; it != last; ++it) {
4        if (*it == value) {
5            return it;
6        }
7    }
8    return last;
9}

Pattern 3: Generic Container

1template <typename T>
2class Queue {
3private:
4    vector<T> elements;
5    
6public:
7    void enqueue(const T& item) {
8        elements.push_back(item);
9    }
10    
11    void dequeue() {
12        if (!elements.empty()) {
13            elements.erase(elements.begin());
14        }
15    }
16    
17    T front() const {
18        return elements.front();
19    }
20};

Template Metaprogramming (Advanced)

Templates can be used for compile-time computation:

1template <int N>
2struct Factorial {
3    static const int value = N * Factorial<N - 1>::value;
4};
5 
6template <>
7struct Factorial<0> {
8    static const int value = 1;
9};
10 
11int main() {
12    cout << Factorial<5>::value << endl;  // Computed at compile time!
13    return 0;
14}

Best Practices

  1. ✅ Use templates for code that works with multiple types
  2. ✅ Prefer typename over class in template declarations
  3. ✅ Use const references for template parameters when possible
  4. ✅ Document template requirements (what operations T must support)
  5. ✅ Use concepts (C++20) for better error messages
  6. ✅ Avoid unnecessary template specialization
  7. ✅ Keep templates in header files (usually)
  8. ✅ Use SFINAE (Substitution Failure Is Not An Error) carefully

Common Mistakes

  • ❌ Forgetting to include template definition in header
  • ❌ Template instantiation errors (unclear error messages)
  • ❌ Circular template dependencies
  • ❌ Not understanding template instantiation
  • ❌ Overusing templates when not needed
  • ❌ Template specialization conflicts

Next Module

In Module 12, we'll learn about Smart Pointers - modern C++ memory management that eliminates many common pointer errors!

Hands-on Examples

Function Templates

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

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

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

// Function template with multiple types
template <typename T, typename U>
void printPair(T first, U second) {
    cout << "Pair: " << first << ", " << second << endl;
}

int main() {
    // Works with integers
    cout << "Max of 10 and 20: " << maximum(10, 20) << endl;
    
    // Works with doubles
    cout << "Max of 3.5 and 2.1: " << maximum(3.5, 2.1) << endl;
    
    // Works with characters
    cout << "Max of 'a' and 'z': " << maximum('a', 'z') << endl;
    
    // Works with strings
    cout << "Max of 'apple' and 'banana': " << maximum(string("apple"), string("banana")) << endl;
    
    // Swap function
    int x = 10, y = 20;
    cout << "\nBefore swap: x = " << x << ", y = " << y << endl;
    swapValues(x, y);
    cout << "After swap: x = " << x << ", y = " << y << endl;
    
    // Multiple types
    printPair(10, "Hello");
    printPair(3.14, 'A');
    
    return 0;
}

Function templates allow you to write one function that works with multiple types. The compiler generates specific versions for each type used. Use typename or class keyword. Templates provide type safety and code reuse without performance overhead.

Sample Output

Max of 10 and 20: 20
Max of 3.5 and 2.1: 3.5
Max of 'a' and 'z': z
Max of 'apple' and 'banana': banana

Before swap: x = 10, y = 20
After swap: x = 20, y = 10
Pair: 10, Hello
Pair: 3.14, A