R
Rishtaara
C++ Fundamentals
Lesson 6 of 8Article18 min

Templates and Generic Programming

Templates let you write reusable code that works with many types while retaining compile-time safety and performance.

Function and class templates

Templates let you write reusable code that works with many types while retaining compile-time safety and performance.

Generic max function
#include <iostream>
using namespace std;

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

int main() {
    cout << maxValue(4, 9) << endl;
    cout << maxValue(4.2, 3.1) << endl;
}

Where templates shine

  • Reusable utilities across data types.
  • STL containers and algorithms are template-based.
  • Enables high-performance abstractions with zero-cost intent.