A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Generics and Template Specialization

Research Depth 101 in the knowledge graph I know this Set as goal
524prerequisites beneath it
See this on the map →
Polymorphism and Type Variables
generics templates code-generation

Core Idea

Generic types and functions are parameterized by type variables and must be monomorphized (specialized) to concrete types for execution. Template instantiation generates type-specific code for each use; monomorphization creates multiple copies, increasing code size but enabling optimization. Languages like C++ use templates; languages like Java use erasure (runtime type information is discarded).

Explainer

You already understand parametric polymorphism — the idea that a function or type can be written once and work with any type that satisfies its constraints. `fn swap<T>(a: T, b: T)` works for integers, strings, or custom structs. But source code generality must eventually become machine code specificity: the CPU executes concrete instructions on concrete data. The compiler must decide how to translate that single generic definition into executable code, and this decision has profound consequences for performance, code size, and runtime behavior.

Monomorphization is the most straightforward strategy. The compiler generates a separate, fully specialized copy of the generic function or type for each concrete type it is used with. If your code calls `swap<i32>` and `swap<String>`, the compiler emits two distinct functions — one operating on 32-bit integers, one on heap-allocated strings — each with its own optimized machine code. This is how C++ templates and Rust generics work. The advantage is zero-cost abstraction: the specialized code is identical to what you would have written by hand for each type, and the optimizer can inline, vectorize, and constant-fold with full type knowledge. The cost is code bloat — if a generic is instantiated with 20 different types, you get 20 copies of the code, which can inflate binary size and pressure instruction caches.

Type erasure takes the opposite approach. Instead of generating specialized copies, the compiler produces a single version of the generic code that operates on a uniform representation — typically object references or pointers. Java generics work this way: `List<Integer>` and `List<String>` share the same bytecode at runtime, with the generic type parameter erased to `Object`. The compiler inserts type casts at boundaries to maintain type safety. This keeps code size small and compilation fast, but sacrifices performance: every operation goes through indirection, primitive types must be boxed into objects, and the optimizer cannot exploit type-specific knowledge.

Modern language implementations explore a spectrum between these extremes. Some compilers monomorphize "hot" instantiations that benefit from specialization while sharing code for less performance-critical ones. Others use dictionary passing, where a generic function receives a table of type-specific operations as an extra argument at runtime — this avoids code duplication while keeping type information available. The compiler's choice of strategy shapes the trade-off triangle between runtime performance, binary size, and compilation speed, and understanding these strategies is essential for both language designers choosing a generics model and systems programmers reasoning about the cost of abstraction.

Practice Questions 5 questions

Prerequisite Chain

Understanding ZeroThe Number ZeroCounting to FiveCounting to 10Counting to 20Counting a Set of Objects Up to 20Cardinality: The Last Number CountedMatching Numerals to QuantitiesSubitizing Small QuantitiesAddition Within 10Number Bonds to 10Addition Within 20Doubles and Near DoublesDoubles Facts Within 10Near Doubles Facts Within 20Mental Math Strategies for AdditionMental Math: Adding and Subtracting TensAddition Within 100Repeated Addition as MultiplicationMultiplication as Equal GroupsMultiplication: ArraysBasic Multiplication Facts (0s, 1s, 2s, 5s, 10s)Multiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Multiplication and Division Fact FamiliesRelationship Between Multiplication and DivisionDivision Facts as Inverse of MultiplicationRemainders and Quotients in DivisionDivision Word ProblemsMulti-Step Word ProblemsSolving Multi-Step Word ProblemsMultiplication Word ProblemsDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueIntegers and the Number LineComparing and Ordering IntegersAbsolute ValueAdding IntegersSubtracting IntegersMultiplying IntegersIntroduction to ExponentsOrder of OperationsInteger Order of OperationsVariable ExpressionsThe Distributive PropertyVariables and Expressions ReviewIntroduction to PolynomialsAdding and Subtracting PolynomialsMultiplying PolynomialsFactorialPermutationsCombinationsCounting Principles: Addition and Multiplication RulesIntroduction to Graph TheoryPropositional Logic FoundationsLogical EquivalencesBoolean AlgebraBoolean Type and Truth ValuesComparison Operators and Boolean TestsLogical Operators and Boolean AlgebraBoolean Algebra and Fundamental LawsLogic Gates FundamentalsImplementing Boolean Functions with GatesKarnaugh Map SimplificationCombinational Circuit DesignFlip-Flops and LatchesFinite State Machines (FSMs)Deterministic Finite Automata (DFA)Nondeterministic Finite Automata (NFA)Two-Way Finite AutomataNFA to DFA Conversion (Subset Construction)DFA Properties and Minimization AlgorithmsRegular Languages: Definition and CharacterizationContext-Free Grammars (CFGs)Context-Free Grammar Properties and AmbiguityParse Trees, Derivations, and Ambiguity in CFGsContext-Free Grammars in Compiler DesignAbstract Syntax Trees (ASTs)Symbol Tables and Scope ResolutionSemantic Analysis PhaseType Systems OverviewUnification AlgorithmType Inference AlgorithmsHindley-Milner Type SystemBidirectional Type CheckingConstraint-Based Type CheckingDependent Types and Value-Level Type ConstraintsSubtyping and Type BoundsPolymorphism and Type VariablesGenerics and Template Specialization

Longest path: 102 steps · 524 total prerequisite topics

Prerequisites (1)

Leads To (0)

No topics depend on this one yet.