In C++, template programming is the secret behind the speed of the standard library. While languages like Java or C# use generics that rely on type erasure and runtime boxes, C++ templates are compiled statically. The compiler generates custom machine instructions for every type you use, yielding zero execution overhead.
Let's look at function template syntax and how the compiler instantiates templates behind the scenes.
Function Templates: Blueprints for Functions
A function template is a blueprint for generating functions. If you want to write a function that finds the maximum of two numbers, you do not want to copy paste the same logic for integer, float, double, and custom classes. Instead, you declare a type parameter T:
Template Instantiation: Stamping Out Code
Here is a critical systems concept: the template definition itself does not occupy any memory in your compiled binary. It is merely a blueprint.
When the compiler parses your code and sees getMax(5, 10), it triggers template instantiation. The compiler takes the template blueprint, replaces T with int, and compiles a real, physical function into machine code. If you never call getMax with a double, the double version is never compiled.
* The Cookie Cutter Metaphor: Think of a template as a cookie cutter. The cookie cutter itself is not a cookie. It does not eat up plate space (executable binary size). But when you press it into dough (call the template with types), you stamp out chocolate cookies (integer function) and vanilla cookies (double function). Each cookie exists physically on the plate, but the cutter remains a guide.
This compilation model is called Monomorphization. It creates exceptionally fast code because there are no pointer checks or dynamic boxes at runtime, but it can increase compilation times and binary sizes (known as code bloat) if you instantiate templates with many different types.
The Header Definition Requirement Trap
When you write normal functions, you declare them in a header file (.h) and write their implementations in a source file (.cpp). Do not do this with templates!
Templates must be defined entirely within header files. Because the compiler compiles each source file (translation unit) independently, it needs to see the actual function template body when instantiating it. If you put a template implementation in a separate .cpp file, compiling another file that calls the template will succeed, but the linker will fail with an undefined reference error because the compiler could not generate the matching type function.