Topic 77 of 83
Templates
Overview
Templates enable Generic Programming. Instead of writing multiple overloaded functions for int, double, and float, you write one template, and the compiler generates the specific versions as needed.
Syntax
cpp
// Function Template
template <typename T>
T findMax(T a, T b) {
return (a > b) ? a : b;
}
// Class Template
template <typename T>
class Box {
T data;
public:
Box(T val) : data(val) {}
T get() { return data; }
};
// Usage
findMax<int>(5, 10);
Box<string> stringBox("Hello");Common Pitfalls
- Placing template declarations in a
.hfile and definitions in a.cppfile will cause Linker Errors. Template definitions MUST be entirely in the header file.
Interview Questions
- Templates are instantiated at COMPILE TIME. If you use a template with an
intand adouble, the compiler creates two completely separate functions in the binary. This can lead to 'Code Bloat'.
Real-World Example
A generic Swap function (similar to std::swap).
example
cpp
#include <iostream>
#include <string>
using namespace std;
template <typename T>
void mySwap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
int main() {
int x = 1, y = 2;
mySwap(x, y); // Compiler deduces T is int
string s1 = "A", s2 = "B";
mySwap(s1, s2); // Compiler deduces T is string
cout << "x:" << x << " y:" << y << endl;
return 0;
}