cs.thefarshad
medium

Templates & Generic Programming

Write code once for any type — the power behind the STL and modern C++ metaprogramming.

How do you write a max(a, b) function that works for int, float, and string without writing three different versions? In C++, you use Templates. This is the foundation of Generic Programming.

A template is not code yet — it is a recipe the compiler follows. Each time you call it with a new type, the compiler stamps out a concrete version; call it again with a type it has already seen and it reuses what it built. Step through the call sites below to watch the instantiations appear.

Template (blueprint)
template <class T>
T myMax(T a, T b) {
  return a > b ? a : b;
}
Call sites
myMax(3, 9);T = int
myMax(2.5, 1.5);T = double
myMax(7, 4);T = int
myMax(s1, s2);T = std::string
Generated code0 instantiation(s)
nothing generated yet
1/6
The template is a blueprint. By itself it generates no machine code — the compiler waits for call sites.

What is a Template?

A template is a blueprint for a function or a class. The compiler uses this blueprint to generate the actual code only when you use the function with a specific type. This is called instantiation.

// A generic function template
template <typename T>
T myMax(T a, T b) {
  return (a > b) ? a : b;
}

int main() {
  // Compiler generates int version:
  int i = myMax(10, 20); 
  
  // Compiler generates double version:
  double d = myMax(3.14, 2.71); 
}

Why use Templates?

  1. Code Reuse: Write logic once and use it for any type that supports the required operations (like the > operator in our max example).
  2. Performance: Because templates are expanded at compile-time, there is zero runtime overhead. The code generated is as fast as if you had written it by hand for that specific type.
  3. Type Safety: The compiler checks that the type you provide actually supports the operations used in the template.

The STL connection

The C++ Standard Template Library (STL) is built entirely on templates. std::vector<T>, std::map<K, V>, and algorithms like std::sort are all templates that can be used with any data type.

Takeaways

  • Templates allow for type-independent, generic code.
  • They are resolved at compile-time, ensuring maximum performance.
  • They power the entire C++ standard library (STL).