🧰 C++ Templates — Generic Functions and Classes Explained
Master C++ templates — function templates, class templates, template specialization, type deduction and how STL uses templates. With examples and interview Q&A.
Templates let you write code that works with any type. The compiler stamps out a specific version for each type you use — generic programming with zero runtime cost.
🔧 Function template
template <typename T>
T max(T a, T b) {
return (a > b) ? a : b;
}
max(3, 7); // T = int
max(2.5, 1.0); // T = double
max<double>(3, 7); // explicit🏗️ Class template
template <typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T get() const { return value; }
};
Box<int> b1(42);
Box<std::string> b2("hi");🎯 Template specialization
Provide a custom implementation for a specific type:
template<>
class Box<bool> {
unsigned bit : 1;
public:
Box(bool b) : bit(b) {}
bool get() const { return bit; }
};📚 Why STL is built on templates
std::vector<int>, std::map<std::string, User> — same code, infinite types. No runtime cost; the compiler generates a fresh copy per type.
💡 Concepts (C++20)
Constrain template parameters: template<Integral T> T add(T a, T b) {...} — clearer errors and intent.
💻 Code Examples
Generic swap
template <typename T>
void mySwap(T& a, T& b) {
T tmp = a; a = b; b = tmp;
}
int x = 1, y = 2; mySwap(x, y); // works for int
std::string a = "hi", b = "bye"; // works for string
mySwap(a, b);Output:
x=2 y=1; a=bye b=hi
Generic container
template <typename T>
class Stack {
std::vector<T> data;
public:
void push(T v) { data.push_back(v); }
T pop() { T t = data.back(); data.pop_back(); return t; }
bool empty() const { return data.empty(); }
};
Stack<int> s; s.push(10); s.push(20);
std::cout << s.pop();Output:
20
Multiple template parameters
template <typename K, typename V>
struct Pair {
K key; V value;
};
Pair<std::string, int> entry{"age", 28};
std::cout << entry.key << '=' << entry.value;Output:
age=28
⚠️ Common Mistakes
- Defining templates in .cpp files — the compiler needs the full definition wherever they're used; put templates in headers.
- Cryptic error messages — modern compilers (Clang, GCC newer) and C++20 concepts help a lot.
- Over-templating simple code — adds compile time and complexity for no real benefit.
- Forgetting `typename` when using a dependent type: `typename T::iterator it;`.
🎯 Interview Questions
Real questions asked at top product and service-based companies.
Q1.What are C++ templates?Intermediate
A compile-time mechanism for writing code that works with any type. The compiler generates a fresh copy for each type used (instantiation). Foundation of generic programming and the STL.
Q2.What's the difference between a function template and a class template?Intermediate
Function template: parameterized function (e.g., `template <typename T> T max(T,T)`). Class template: parameterized class (e.g., `template <typename T> class Vector`). Both generate type-specific code at compile time.
Q3.What is template specialization?Advanced
Providing a CUSTOM IMPLEMENTATION of a template for a specific type. Full specialization: `template<> class Box<bool>`. Partial specialization: only for class templates, e.g., `template<typename T> class Box<T*>`. Used to optimize or change behavior for specific types.
Q4.Why are templates header-only in C++?Advanced
The compiler needs the full template definition wherever it's instantiated to generate the type-specific code. If the definition lived in a .cpp file, other files couldn't instantiate it. So template definitions go in headers.
Q5.What are C++20 concepts?Advanced
Compile-time constraints on template parameters. Instead of accepting any type and failing deep inside the template, you say `template<Integral T>` — clearer errors, better tooling, self-documenting code.
🧠 Quick Summary
- Templates = write code once, works for any type.
- Function templates and class templates.
- Specialization = custom code for specific types.
- STL is entirely template-based.
- Templates live in headers.
- C++20 concepts constrain type parameters cleanly.