Intermediate Topic 21 of 50 Languages & Compilers
Generics and Templates
Writing code parameterized over types.
How it works
Generics let you write code that works with many types while keeping type safety, parameterizing classes and functions by type, as in List of T or max of T. Implementations differ: Java erases type parameters at run time, C# keeps them reified, Rust and C++ templates monomorphize by generating specialized code per type, and constraints such as traits, interfaces and concepts restrict what types are allowed. They enable reusable containers and algorithms without casts.
Step-by-step walkthrough
- One definition is written for any type T.
- It is instantiated with int.
- It is instantiated with string.
- Each use is type-checked.
- No casts or duplicate code are needed, and C++ templates are expanded at compile time.
Where it is used
Collections, smart pointers, option and result types, sorting and numeric libraries, and frameworks use generics extensively.
Common pitfall
Type erasure limits what generics can do at run time, such as creating arrays of T or checking instanceof. Template code can bloat binaries and produce long, confusing error messages in C++. Variance, covariance versus contravariance, causes subtle errors with subtyping. Use constraints, keep generic code simple and test with several type arguments.
Where it fits in the course
Generics and Templates is topic 21 of 50 in Languages & Compilers, rated Intermediate. It follows Type Inference. The next topic is Compiler Phases.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Languages & Compilers quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Languages & Compilers quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Generics and Templates?
Where do people use Generics and Templates?
What is the most common mistake with Generics and Templates?
What should I learn before this topic?
How can I practice it?
Is Generics and Templates hard to learn?
How long does it take to learn Generics and Templates?
Which topics are related to Generics and Templates?
What should I study after Generics and Templates?
Related topics
- Type Inference (Languages & Compilers)
- Compiler Phases (Languages & Compilers)
- Semantic Analysis (Languages & Compilers)
- Recursive Descent Parsing (Languages & Compilers)