Module 22: Templates in C++
Templates are one of the most powerful features of C++. They allow you to write generic and reusable code that works with different data types without duplicating code.
Instead of writing separate functions or classes for int, float, double, or string, templates let you write the code once and use it with any data type.
Templates are widely used in the Standard Template Library (STL), including containers like vector, list, map, and algorithms like sort().
Advantages of Templates
- Code reusability
- Type safety
- Better maintainability
- Reduced code duplication
- High performance (compile-time type checking)
1. Function Templates
A function template allows a single function to operate on different data types.
Syntax
1template <typename T> 2returnType functionName(parameters) 3{ 4 // Function body 5}
typenameandclassare interchangeable in template declarations.
Example
1#include <iostream> 2 3using namespace std; 4 5template <typename T> 6T maximum(T a, T b) 7{ 8 return (a > b) ? a : b; 9} 10 11int main() 12{ 13 cout << maximum(10, 20) << endl; 14 cout << maximum(5.5, 3.2) << endl; 15 cout << maximum('A', 'Z'); 16 17 return 0; 18}
Output
120 25.5 3Z
Multiple Template Parameters
1#include <iostream> 2 3using namespace std; 4 5template <typename T, typename U> 6void display(T a, U b) 7{ 8 cout << a << " " << b; 9} 10 11int main() 12{ 13 display(10, "C++"); 14 15 return 0; 16}
Output
110 C++
2. Class Templates
A class template allows a class to work with different data types.
Syntax
1template <class T> 2class ClassName 3{ 4};
Example
1#include <iostream> 2 3using namespace std; 4 5template <typename T> 6class Box 7{ 8private: 9 T value; 10 11public: 12 Box(T v) 13 { 14 value = v; 15 } 16 17 void display() 18 { 19 cout << value; 20 } 21}; 22 23int main() 24{ 25 Box<int> box1(100); 26 Box<double> box2(45.75); 27 Box<string> box3("Tech3Space"); 28 29 box1.display(); 30 cout << endl; 31 32 box2.display(); 33 cout << endl; 34 35 box3.display(); 36 37 return 0; 38}
Output
1100 245.75 3Tech3Space
3. Template Specialization
Sometimes a generic template is not suitable for every data type. Template specialization allows you to provide a custom implementation for a specific type.
Generic Template
1#include <iostream> 2 3using namespace std; 4 5template <typename T> 6class Printer 7{ 8public: 9 void print(T value) 10 { 11 cout << value; 12 } 13};
Specialized Template
1#include <iostream> 2 3using namespace std; 4 5template <> 6class Printer<string> 7{ 8public: 9 void print(string value) 10 { 11 cout << "String: " << value; 12 } 13}; 14 15int main() 16{ 17 Printer<int> p1; 18 Printer<string> p2; 19 20 p1.print(10); 21 cout << endl; 22 23 p2.print("Hello"); 24 25 return 0; 26}
Output
110 2String: Hello
4. Variadic Templates
Variadic templates (introduced in C++11) allow functions and classes to accept any number of arguments.
They are widely used in modern C++ libraries.
Example
1#include <iostream> 2 3using namespace std; 4 5void print() 6{ 7 cout << endl; 8} 9 10template <typename T, typename... Args> 11void print(T first, Args... args) 12{ 13 cout << first << " "; 14 15 print(args...); 16} 17 18int main() 19{ 20 print(10, 20.5, "C++", 'A'); 21 22 return 0; 23}
Output
110 20.5 C++ A
How Variadic Templates Work
1print(10,20,"Hello") 2 3↓ 4 5print(10, print(20,"Hello")) 6 7↓ 8 9print(20, print("Hello")) 10 11↓ 12 13print("Hello") 14 15↓ 16 17End
Function Template vs Class Template
| Function Template | Class Template |
|---|---|
| Creates generic functions | Creates generic classes |
| Works with different parameter types | Works with different object types |
| Easier to write | Used for reusable data structures |
Example: max() | Example: vector<T> |
Common STL Templates
| Template | Purpose |
|---|---|
vector<T> | Dynamic array |
list<T> | Doubly linked list |
stack<T> | Stack |
queue<T> | Queue |
map<K,V> | Key-value pairs |
set<T> | Unique values |
pair<T,U> | Two related values |
Best Practices
- Use templates to avoid duplicate code.
- Prefer
typenamefor readability. - Use template specialization only when necessary.
- Keep template implementations in header files because templates are instantiated at compile time.
- Use variadic templates instead of C-style variable argument lists (
...).
Practice Problems
- Write a function template to swap two values.
- Create a function template to find the minimum of two numbers.
- Build a generic
Stack<T>class. - Create a generic
Pair<T1, T2>class. - Specialize a template for the
stringdata type. - Write a variadic template that calculates the sum of multiple numbers.
Interview Questions
- What are templates in C++?
- What is the difference between function templates and class templates?
- What is generic programming?
- What is template specialization?
- What are variadic templates?
- What is the difference between
typenameandclassin template declarations? - Why are template definitions usually placed in header files?
- What are the advantages of templates?
- Where are templates commonly used in the STL?
Summary
In this module, you learned:
- What templates are and why they are important in C++.
- How function templates create reusable generic functions.
- How class templates build reusable generic classes.
- How template specialization customizes behavior for specific data types.
- How variadic templates accept any number of arguments.
- Best practices for writing efficient, reusable, and type-safe generic code.
Next Module: Module 23: Standard Template Library (STL) — Containers, Iterators, Algorithms, Functors, Lambda Expressions, Smart Pointers, and Practical STL Applications.