› Module 6: Templates & Generic Programming › 6.1 Function Templates
M O D U L E

Module 6: Templates & Generic Programming

Writing code once that works for any data type — function templates, class templates, and STL specialization.

6.1 Function Templates

Without templates you would need a separate max() function for int, double, char, and every other type, all with identical logic.

A function template lets you write that logic once using a placeholder type, conventionally named T; the compiler then generates a specific version for whichever type you actually use, entirely at compile time, with zero runtime cost.

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

maxVal(3, 7);       // instantiates an int version
maxVal(2.5, 1.1);   // instantiates a double version
template <typename T> T max(T a, T b) max<int>(3, 7) compiles int version max<double>(2.5, 1.1) compiles double version max<char>('a', 'z') compiles char version
Figure 6.1 — One template, compiled into many type-specific functions

6.2 Class Templates

Just like functions, entire classes can be templated. This is exactly how the Standard Template Library's containers, like vector, work internally: one class definition that can hold ints, strings, or your own custom objects, all fully type-checked at compile time.

template <typename T>
class Box {
    T value;
public:
    Box(T v) : value(v) {}
    T get() { return value; }
};

Box<int> b1(10);
Box<string> b2("hi");

6.3 Templates + STL

Templates are the reason the Standard Template Library can be both generic and fast: its containers and algorithms are written once as templates and then specialized by the compiler for whatever type you plug in, with no runtime overhead compared to hand-writing a type-specific version yourself.

vector<int> nums = {1, 2, 3};
vector<string> names = {"Ann", "Bob"};
// Same vector template, two completely different high-performance compiled types!
MODULE COMPREHENSIVE QUIZ

Module 6 Final Quiz

Test your understanding across all 3 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 6 Final Quiz →
Yukti Mascot