Generic programming writes an algorithm or container once and reuses it for many types. C++ does it with templates (code generated per type at compile time); Java with generics (type-checked, then erased). Know templates, specialization, the STL, bounds, wildcards and erasure's limits.
Medium 50 minSyllabus: “Generic classes”
Mark as
The idea in one minute
A cookie cutter does not care whether the dough is chocolate or vanilla — the shape is the same. A template is a cookie cutter for code: write maxOf or Stack once with a placeholder type T, and the compiler stamps out an int version, a double version, a string version as needed. Java's generics are more like labelled boxes: the label List<String> is checked whenever you put things in or take them out, but inside the warehouse every box looks the same.
Key points — the night-before list
template <typename T> T maxOf(T a, T b) is a function template; typename and class are interchangeable here, and T is deduced from the arguments.
Deduction needs one consistent type: maxOf(3, 4.5) fails (int vs double); maxOf<double>(3, 4.5) works. An exact non-template match beats a template.
Class template: template <class T, int N> class Stack; objects need explicit arguments (Stack<int, 10>); N is a non-type parameter — a compile-time constant.
Instantiation: the compiler generates separate code for each distinct argument list used (possible code bloat); template definitions usually live in headers.
Specialization: template <> class Stack<bool> (full); partial specialization (e.g. for all T*) is allowed for class templates only.
Java generics (Java 5): class Box<T>, generic methods <T> void f(T x), bounds <T extends Number>; type arguments must be reference types — List<Integer>, never List<int>.
? extends T = read/produce, ? super T = write/consume (PECS). Erasure: no new T(), no new T[n]; List<Integer> is not a List<Number>.
01Why generic code?
Suppose you need 'the larger of two values' for ints, doubles and strings. Without generics you either write three nearly identical functions (overloading — the logic is duplicated), use a macro (no type checking), or work with untyped void* / Object (casts everywhere, and type errors surface only at run time).
Generic programming writes the algorithm once in terms of a type that is supplied later. In C++ this is done with templates — a form of compile-time (parametric) polymorphism; in Java with generics. The compiler checks that each use makes sense for the type actually supplied.
Overloaded functions
One hand-written body per type
Bodies may do genuinely different things
A new type means writing a new function
Best when the behaviour differs by type
A function template
One body; the compiler writes each version
The same algorithm for every type
New types work automatically if they support the operations used
Best when only the type differs
02Function templates
A function template is introduced by template <typename T> (or, equivalently, template <class T>) in front of an ordinary-looking function that uses T as a type. When you call it, the compiler deduces T from the argument types and generates a matching function.
C++Deduction, explicit arguments and a specialization (prints: 7 / 2.5 / 4.5 / pear / mango / 7.5)
#include <iostream>#include <string>#include <cstring>
using namespace std;
template <typename T>
T maxOf(T a, T b) {
return (a > b) ? a : b;
}
// full specialization: C-strings must be compared by content, not by address
template <>
const char* maxOf<const char*>(const char* a, const char* b) {
return (strcmp(a, b) > 0) ? a : b;
}
template <class T, class U> // two independent type parameters
auto addMixed(T a, U b) { return a + b; }
int main() {
cout << maxOf(3, 7) << "\n"; // T = int
cout << maxOf(2.5, 1.5) << "\n"; // T = double
cout << maxOf<double>(3, 4.5) << "\n"; // T given explicitly
cout << maxOf(string("pear"), string("apple")) << "\n"; // T = string
cout << maxOf("apple", "mango") << "\n"; // uses the specialization
cout << addMixed(3, 4.5) << "\n"; // int + double// cout << maxOf(3, 4.5); // error: T deduced as int AND as double
}
Every argument that mentions T contributes to deduction; if they disagree (int and double), the template is discarded and the call fails.
No implicit conversions are applied while deducing — even the harmless int → double.
You can always state T yourself: maxOf<double>(3, 4.5) converts 3 to 3.0.
If an ordinary (non-template) function matches exactly, it is preferred over the template; show<>(5) forces the template.
A template places implicit requirements on T: maxOf needs > and copying. Calling it with a type that has no > fails at compile time — usually with a long error message pointing inside the template. C++20 concepts let you state such requirements explicitly.
03Class templates and non-type parameters
A class template describes a family of classes — Stack<int>, Stack<string> — whose members use the type parameter. Unlike function templates, the arguments are normally written explicitly when declaring an object. A member function defined outside the class repeats the template header and names the class with its parameters: template <class T, int N> bool Stack<T, N>::push(const T& x).
C++A bounded stack with a type parameter and a non-type parameter
#include <iostream>#include <string>
using namespace std;
template <class T, int N = 4> // N: non-type parameter (a compile-time constant)
class Stack {
T data[N];
int top = -1;
public:
bool push(const T& x);
bool pop(T& out);
int size() const { return top + 1; }
static int capacity() { return N; }
};
template <class T, int N> // member defined outside: repeat the header
bool Stack<T, N>::push(const T& x) {
if (top == N - 1) return false; // full
data[++top] = x;
return true;
}
template <class T, int N>
bool Stack<T, N>::pop(T& out) {
if (top == -1) return false; // empty
out = data[top--];
return true;
}
int main() {
Stack<int, 3> s; // the class Stack<int, 3> is instantiated
for (int i = 1; i <= 4; i++)
cout << "push " << i << (s.push(i * 10) ? " ok" : " FULL") << "\n";
int v;
while (s.pop(v)) cout << "pop " << v << "\n";
Stack<string> names; // N takes its default, 4
names.push("Asha");
cout << names.size() << " of " << Stack<string>::capacity() << "\n";
}
/* Output: push 1 ok / push 2 ok / push 3 ok / push 4 FULL / pop 30 / pop 20 / pop 10 / 1 of 4 */
A non-type template parameter is a value rather than a type — typically an integer, enumerator or pointer. Its argument must be a compile-time constant: with int n = 5;, Stack<int, n> is rejected ('non-type template argument is not a constant expression'). Each distinct argument list is a distinct, unrelated type: a Stack<int, 3> cannot be assigned to a Stack<int, 4>. Template parameters may have defaults, as N = 4 shows.
04Instantiation and specialization
A template is not code yet — it is a recipe. Instantiation is the compiler generating real code for specific template arguments, normally the first time they are used (implicit instantiation); template class Stack<int, 10>; requests it explicitly. Because the compiler needs the whole recipe at that point, template definitions are usually placed in header files; putting them in a separate .cpp file typically causes 'undefined reference' link errors.
Every distinct instantiation produces its own machine code, so heavy use of templates can enlarge the program (code bloat) — the price of generic code that runs as fast as hand-written code.
Specialization supplies a custom version for particular arguments. A full (explicit) specialization, introduced by template <>, replaces the template for one exact argument list — maxOf for const char* above. A partial specialization covers a whole family, such as every pointer type T*; it exists only for class templates (function templates achieve the same effect by overloading).
C++Primary template, partial and full specialization; non-template preference (prints: general holder / pointer holder / bool holder / plain int / template / template)
#include <iostream>
using namespace std;
template <class T> class Holder { // primary template
public:
void info() { cout << "general holder\n"; }
};
template <class T> class Holder<T*> { // partial specialization: any pointer type
public:
void info() { cout << "pointer holder\n"; }
};
template <> class Holder<bool> { // full specialization
public:
void info() { cout << "bool holder\n"; }
};
template <class T> void show(T) { cout << "template\n"; }
void show(int) { cout << "plain int\n"; }
int main() {
Holder<double>().info(); // general holder
Holder<int*>().info(); // pointer holder
Holder<bool>().info(); // bool holder
show(5); // plain int (an exact non-template match wins)
show(5.0); // template
show<>(5); // template (empty <> forces the template)
}
Watch out
Without the const char* specialization, maxOf("apple", "mango") would compare the two addresses of the string literals, not their text — the answer depends on where the compiler happened to store them.
05The Standard Template Library in brief
The Standard Template Library (STL) was designed by Alexander Stepanov (with Meng Lee) at Hewlett-Packard and adopted into the C++ standard in 1994, becoming part of C++98. Its key idea is to separate data structures from algorithms: containers expose iterators, and algorithms are function templates that work on any iterator range.
Component
What it is
Examples
Sequence containers
Elements kept in insertion order
vector (dynamic array), deque, list (doubly linked), array, forward_list
#include <iostream>#include <vector>#include <algorithm>#include <numeric>#include <map>#include <string>
using namespace std;
int main() {
vector<int> marks = {72, 95, 60, 88, 95};
sort(marks.begin(), marks.end()); // ascending
for (int m : marks) cout << m << " ";
cout << "\n";
cout << count(marks.begin(), marks.end(), 95) << " " // how many 95s
<< accumulate(marks.begin(), marks.end(), 0) << " " // sum
<< binary_search(marks.begin(), marks.end(), 88) << "\n"; // needs sorted data
reverse(marks.begin(), marks.end());
cout << marks.front() << " " << marks.back() << "\n";
map<string, int> seats = {{"Kochi", 120}, {"Alappuzha", 80}};
seats["Thrissur"] = 95; // insert through []
for (const auto& kv : seats) cout << kv.first << "=" << kv.second << " "; // sorted keys
cout << "\n";
}
06Java generics: type parameters, generic methods and bounds
Java added generics in J2SE 5.0 (2004). Before that, collections stored plain Object; every read needed a cast, and a wrong element surfaced only as a ClassCastException at run time. A generic class declares type parameters in angle brackets; a generic method declares its own before the return type; a bounded type parameter restricts what may be supplied.
JavaA generic class, a generic method and a bounded method (prints: 1 2 3 / KSHB 155.0)
import java.util.ArrayList;
import java.util.List;
class Box<T> { // T: a type parameter
private T item;
void put(T item) { this.item = item; }
T get() { return item; }
}
public class GenericsDemo {
static <T> void printAll(T[] items) { // generic method: <T> before the return type
for (T t : items) System.out.print(t + " ");
System.out.println();
}
static <T extends Number> double sum(List<T> list) { // bounded type parameter
double total = 0;
for (T n : list) total += n.doubleValue(); // legal: every T is a Number
return total;
}
public static void main(String[] args) {
Box<String> b = new Box<>(); // diamond operator (Java 7) infers <String>
b.put("KSHB");
String s = b.get(); // no cast needed// b.put(42); // compile error: int is not a String
printAll(new Integer[] {1, 2, 3});
List<Integer> marks = new ArrayList<>();
marks.add(70); // autoboxing int -> Integer
marks.add(85);
System.out.println(s + " " + sum(marks));
}
}
Conventional names are single capitals: T type, E element, K key, V value, N number. Several bounds can be combined, class first: <T extends Number & Comparable<T>>. Type arguments must be reference types — List<int> is illegal — so primitives travel as their wrapper classes through autoboxing.
Generic types are invariant: List<Integer> is not a subtype of List<Number>, even though Integer is a Number. If it were, you could add a Double to a list of Integers through the Number view. Arrays chose the opposite (covariance) and pay for it at run time:
JavaCovariant arrays fail late; invariant generics fail early
Object[] objs = new Integer[2];
objs[0] = "text"; // compiles, but throws ArrayStoreException at run time
List<Integer> ints = new ArrayList<>();
// List<Number> nums = ints; // compile error: incompatible types
07Wildcards, type erasure and raw types
A wildcard? stands for an unknown type and restores flexibility. List<?> is a list of something: you can read elements as Object but cannot add (except null). List<? extends Number> (upper bound) accepts a list of Integer, Double or any Number subtype — you can read Numbers from it but not add to it. List<? super Integer> (lower bound) accepts a list of Integer, Number or Object — you can add Integers to it, but reads give only Object.
import java.util.*;
public class Wild {
static double total(List<? extends Number> src) { // producer: we only READ from it
double t = 0;
for (Number n : src) t += n.doubleValue();
return t;
}
static void fill(List<? super Integer> dst) { // consumer: we only WRITE to it
for (int i = 1; i <= 3; i++) dst.add(i);
}
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>(List.of(4, 5));
List<Double> dbls = List.of(1.5, 2.5);
List<Object> objs = new ArrayList<>();
System.out.println(total(ints) + " " + total(dbls));
fill(objs); // Object is a supertype of Integer
fill(ints);
System.out.println(objs + " " + ints);
// fill(dbls); // error: Double is not a supertype of Integer
}
}
The mnemonic is PECS — Producer Extends, Consumer Super (Joshua Bloch, Effective Java). Collections.copy(List<? super T> dest, List<? extends T> src) is the textbook example: it reads from src and writes into dest.
Java implements generics by type erasure: the compiler checks every use against the type arguments, then erases them — replacing T by its bound (Object, or the first bound) and inserting casts. Only one class file exists for Box, whatever T is. That keeps old and new code compatible, but has visible consequences:
No new T() and no new T[n] — T is unknown at run time.
No primitive type arguments: use List<Integer>, not List<int>.
No obj instanceof List<String> (only instanceof List<?>), and there is no List<String>.class.
Static fields are shared by every parameterisation — Box<String> and Box<Integer> are the same run-time class.
Overloads that erase to the same signature clash: void f(List<String>) and void f(List<Integer>) cannot coexist.
No generic array creation such as new List<String>[10], and a generic class cannot extend Throwable.
A raw type is a generic type used without arguments — List list = new ArrayList(); — the pre-Java-5 style. It still compiles for backward compatibility, but with 'unchecked' warnings and no type safety: anything can be added, and the mistake surfaces later as a ClassCastException.
Point
C++ templates
Java generics
Mechanism
Code generated per argument list (instantiation)
One class; type arguments erased after checking
Checked when
At instantiation, for the actual types
At compile time, against the declared bounds
Primitive arguments
Yes: vector<int>
No: List<Integer> with boxing
Non-type parameters
Yes: template <int N>
No
new T(), sizeof(T)
Allowed
Not allowed — the type is unknown at run time
Specialization
Full and partial
Not available
Run-time type
Each instantiation is a distinct type
Lost: List<String> and List<Integer> share one Class
Code size
Grows with each instantiation
No growth per type
Constraints
Implicit (C++20 adds concepts)
Explicit bounds: <T extends Number>
C++ templates vs Java generics
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Function-template deduction, call by call
For template <typename T> T maxOf(T a, T b) plus the const char* specialization, give the result (or error) of: maxOf(3, 7), maxOf(2.5, 1.5), maxOf<double>(3, 4.5), maxOf(string("pear"), string("apple")), maxOf("apple", "mango") and maxOf(3, 4.5).
EX 2Tracing a class template with a non-type parameter
For Stack<int, 3> s; from Section 3, trace four calls s.push(i * 10) for i = 1…4, then while (s.pop(v)) printing v.
EX 3Java: which generic calls compile?
With static <T extends Number> double sum(List<T> list), static double total(List<? extends Number> src) and static void fill(List<? super Integer> dst), decide: (a) sum(List<Integer>) (b) sum(List<String>) (c) total(List<Double>) (d) fill(List<Number>) (e) fill(List<Double>) (f) List<Number> n = new ArrayList<Integer>(); (g) List<? extends Number> m = new ArrayList<Integer>(); m.add(5);
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Write a function template swapValues that swaps two variables of the same type. What is printed for ints 3 and 9 and strings "Kochi" and "Kannur" (printed in the order x y p q after swapping)? What happens with int a; double b; swapValues(a, b);?
Q2
Predict the six lines printed by the Holder / show program in Section 4, and explain the last two.
Q3
Java: mark each as compiles / error: (a) List<int> a; (b) List<Integer> b = new ArrayList<>(); (c) List<Object> c = new ArrayList<String>(); (d) List<? extends Number> d = new ArrayList<Integer>(); (e) d.add(5); (f) inside class Box<T>: T t = new T();
Q4
What does this print? vector<int> v = {5, 1, 4}; v.push_back(2); sort(v.begin(), v.end()); reverse(v.begin(), v.end()); then the elements, v.size(), v.front(), v.back() and find(v.begin(), v.end(), 4) - v.begin().
Q5
Why does static <T> T[] make(int n) { return new T[n]; } not compile? Give two workarounds.
Exam traps
List<Integer> is not a List<Number> (generics are invariant), yet Integer[]is an Object[] (arrays are covariant and fail later with ArrayStoreException).
typename and class mean the same in a template parameter list — but typename is required to name a dependent nested type, as in typename T::iterator.
C++ generates separate code per instantiation; Java keeps one class (erasure), so Box<String> and Box<Integer> share static fields and one Class object.
Primitives cannot be Java type arguments — List<int> is illegal; templates accept vector<int> directly.
Template definitions must be visible where they are used — put them in headers, or expect linker errors.
Template argument deduction applies no conversions: maxOf(3, 4.5) fails even though int → double is normally automatic.
Quiz — KPSC style
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.