C++ - Templates & Generic Programming in C++
Templates allow you to write generic code — code that works with any data type without rewriting it.
Instead of duplicating logic for int, double, string, etc., you write it once.
1. Function Templates
Problem Without Templates
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
Duplicate logic.
Solution: Function Template
template <typename T>
T add(T a, T b) {
return a + b;
}
Usage:
add(5, 3); // T = int
add(2.5, 4.3); // T = double
The compiler generates the correct version automatically.
How It Works
T is a placeholder type.
The compiler replaces T with the actual type at compile time.
This is called compile-time polymorphism.
2. Class Templates
Used when creating generic classes.
Example: Simple container.
template <typename T>
class Box {
private:
T value;
public:
void set(T v) { value = v; }
T get() { return value; }
};
Usage:
Box<int> intBox;
Box<double> doubleBox;
Each instantiation creates a separate version.
3. Multiple Template Parameters
template <typename T, typename U>
class Pair {
public:
T first;
U second;
};
Usage:
Pair<int, string> p;
4. Template Specialization
Sometimes you want custom behavior for a specific type.
template <typename T>
class Printer {
public:
void print(T value) {
std::cout << value;
}
};
Specialization:
template <>
class Printer<char*> {
public:
void print(char* value) {
std::cout << "String: " << value;
}
};
This overrides the generic version.
5. Variadic Templates (Advanced)
Used when number of parameters is unknown.
template <typename... Args>
void printAll(Args... args) {
(std::cout << ... << args);
}
This uses a fold expression (C++17).
6. Non-Type Template Parameters
Templates can also accept constant values.
template <int N>
class Array {
int arr[N];
};
Usage:
Array<10> obj;
N must be compile-time constant.
7. Why Templates Are Important
-
Used heavily in Standard Template Library (STL)
-
Enables high performance (no runtime overhead)
-
Type-safe generic programming
-
Core for modern C++ libraries
Example:
std::vector<int>
std::vector<double>
std::vector itself is a class template.
Key Concepts for Interviews
-
Template instantiation happens at compile time.
-
Templates increase code bloat if overused.
-
Use
typenameorclass(both are valid). -
Templates cannot be separated easily like normal classes (definition usually in header).