TeachMate
My ProgressJoin Session

Templates

0/8 completed · ~0h 34m

All Topics
C++LearnTemplates
1 / 8

Function Templates

advanced
4 min read

Templates let you write generic code that works with any type.

Basic Template

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

Usage

int main() {
    cout << getMax(5, 10);
    cout << getMax(3.14, 2.72);
    cout << getMax('a', 'z');
    // Type is deduced from arguments
}

Explicit Type Specification

cout << getMax<double>(5, 10);  // Forces double

Multiple Template Parameters

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

Function Template Overloading

template <typename T>
void print(T x) {
    cout << x;
}

template <typename T>
void print(T* p) {  // Overload for pointers
    cout << *p;
}

How Templates Work

  1. Compiler sees template usage
  2. Generates specific code for the type used
  3. Compiles the generated code
// Template definition
template <typename T>
T getMax(T a, T b) { return (a > b) ? a : b; }

// Compiler generates:
// int getMax(int a, int b) { ... }
// double getMax(double a, double b) { ... }
// char getMax(char a, char b) { ... }

Templates are compile-time: no runtime overhead.

Templates generate code at compile time. Each unique type combination creates a new copy of the template. This can lead to large binary sizes (code bloat).

Key takeaway: Function templates let the compiler generate type-specific code — zero runtime overhead, but each type creates a new instantiation.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects