Labs ICT
โญ Pro Login

Templates

C++ Templates

Templates enable generic programming โ€” writing code that works with any data type. Instead of writing separate functions or classes for int, double, string, etc., you write one template and let the compiler generate the appropriate code. This is the foundation of the entire STL.

#include <iostream>

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

int main() {
    std::cout << getMax(10, 20) << "\n";
    std::cout << getMax(3.14, 2.71) << "\n";
    std::cout << getMax('A', 'Z');
    return 0;
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What does a template allow you to do?