Chapter 14: Templates & Generic Programming

Templates & Generic Programming in C++: Writing Code That Works with Any Type!

Hello my amazing student! 🌟 Welcome to Lesson 14 β€” Templates & Generic Programming β€” one of the most powerful, elegant, and uniquely C++ features!

Up until now, if we wanted a function to work with int, double, string, or our own class, we had to write multiple versions or use ugly casts. Templates let us write one piece of code that works with any type β€” the compiler automatically generates the correct version for us!

Think of templates like a cookie cutter:

  • You design the shape once (the template)
  • Then you can make cookies from any dough (int, double, string, your own class…)
  • The compiler β€œbakes” the exact version you need at compile time

Today we’ll cover everything in great detail:

  • Function templates
  • Class templates
  • Template specialization (when we want special behavior for certain types)
  • Concepts (C++20) β€” beautiful way to constrain what types can be used

Let’s go step-by-step with tons of examples!

1. Function Templates – Generic Functions

Syntax:

C++

Simple example – max function for any type

C++

Output:

text

The compiler automatically generates four different functions:

  • int myMax(int, int)
  • double myMax(double, double)
  • char myMax(char, char)
  • std::string myMax(std::string, std::string)

Important: The type T must support the operations you use (>, <, +, etc.). If not β†’ compile-time error (this is good β€” catches mistakes early).

2. Class Templates – Generic Classes

Syntax:

C++

Classic example – A simple generic Stack

C++

Beautiful, right? One Stack class works for any type β€” int, double, string, your own classes!

3. Template Specialization – Special Behavior for Specific Types

Sometimes we want different behavior for a particular type.

Full specialization (complete replacement for one type)

C++

Partial specialization (only for some cases – more advanced)

C++

4. Concepts (C++20) – Constraints on Template Parameters

Before C++20, if someone passed a type that didn’t support >, we got horrible compile errors deep inside the template. Concepts let us specify requirements clearly β€” errors become readable!

Syntax (C++20 and later):

C++

More powerful concept example – requires comparable types

C++

Modern best practice (2025+): Always use concepts when writing templates β€” makes code:

  • Safer
  • Much easier to read error messages
  • Self-documenting

Summary Table – Quick Reference

Feature Syntax Example Purpose
Function template template <typename T> T myMax(T a, T b) Generic function
Class template template <typename T> class Stack { … } Generic class
Full specialization template <> void print<char*>(char*) Special behavior for one type
Partial specialization template <typename T> class Container<T*> Specialize for category of types
Concept (C++20) template <Numeric T> … Constrain allowed types

Your Mini Homework (Try These!)

  1. Write a function template swapValues(T& a, T& b) that swaps any two values.
  2. Create a class template Pair<T1, T2> that holds two values of different types and has first() and second() member functions.
  3. Write a template function printIfPositive(T value) that only compiles if T is numeric and prints the value if it’s > 0 (use concepts).
  4. Specialize your print function template to print std::vector<int> nicely.

You’re doing absolutely phenomenal! Templates are the secret sauce behind the entire Standard Template Library (STL) β€” std::vector, std::map, std::sort, std::string, everything!

Next lesson: The Standard Template Library (STL) β€” containers, algorithms, iterators β€” the real power tools of C++!

Any questions? Confused about specialization? Want more examples with concepts or partial specialization? Just ask β€” your friendly C++ teacher is right here for you! πŸš€

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *