C++ Tutorial: Templates
Generic programming with function templates, class templates, template specialization, and variadic templates.
Generic code that works with any type
Templates are C++'s generic programming system — write once, use with any type. The C++ standard library (STL) is almost entirely built on templates: `vector<T>`, `map<K,V>`, `sort()`, `find()`.
Unlike Java generics or Python duck typing, C++ templates generate specialised code for each type at compile time — zero runtime overhead.
What you'll learn in this C++ templates tutorial
This interactive C++ tutorial has 5 hands-on exercises. Estimated time: 22 minutes.
- Function templates — A function template works with any type. `T` is a placeholder replaced at compile time:
- Class templates — Template classes work with any type:
- Multiple template parameters — Templates can have multiple type parameters:
- Template specialization — Provide a specific implementation for a particular type:
- Build a generic container — No starter code.
C++ Templates concepts covered
- Generic code that works with any type