Templates (Generics)
Overview
If you write a function int max(int a, int b), and later need to find the maximum of two doubles, you have to write a second function using Overloading. If you need it for strings, you write a third. This is exhausting and prone to typos.
C++ introduced Templates (often called Generics in Java/C#). A Template allows you to write a single master blueprint of a function (or Class) where the exact Data Type is left completely blank (usually represented by the letter T). When you finally call the function, the C++ Compiler analyzes your data, dynamically fills in the blank, and physically generates the mathematically correct code in the background.
Syntax
#include <iostream>
// 1. THE TEMPLATE DEFINITION
// We tell the compiler: "T represents a generic, unknown data type"
template <typename T>
T getMaximum(T a, T b) {
return (a > b) ? a : b;
}
int main() {
// 2. EXECUTING THE TEMPLATE
// The compiler sees we passed integers. It secretly generates an 'int' version of the function!
std::cout << getMaximum<int>(10, 50) << "\n"; // Prints 50
// The compiler sees doubles. It secretly generates a 'double' version!
std::cout << getMaximum<double>(3.14, 2.71) << "\n"; // Prints 3.14
// Modern C++ feature: The <type> can often be completely omitted!
// The compiler just infers it based on the arguments!
std::cout << getMaximum(100, 200) << "\n";
return 0;
}Common Pitfalls
- Template Code Bloat. Templates do NOT save binary file size. If you call
getMaximumwith 15 different data types across your project, the compiler physically generates and compiles 15 completely separate functions in your final executable, which can balloon the.exesize significantly. - The Header File Trap. Unlike standard functions, you CANNOT separate a Template's Declaration (in the
.hfile) from its Definition (in the.cppfile). Because the compiler needs to see the full code to generate the types dynamically, the entire Template body MUST be written directly inside the header file.
Interview Questions
Templates are evaluated strictly at Compile-Time. The compiler scans your entire project, logs every single Data Type you used the template with, and hardcodes those specific functions into the binary before the program ever runs. This guarantees absolutely zero runtime performance overhead.
Real-World Example
Building a generic Class Template. This is the exact architectural foundation of std::vector!
#include <iostream>
// The Class can now hold ANY data type!
template <typename T>
class Box {
private:
T item;
public:
Box(T i) : item(i) {}
T getItem() { return item; }
};
int main() {
Box<int> intBox(99);
Box<std::string> strBox("Hello");
std::cout << intBox.getItem() << "\n";
return 0;
}Check Your Knowledge
Test your understanding of Templates (Generics) with these quick questions.