Templates in C++
Introduction
Templates are an important feature of C++ that allow us to write generic and reusable code.
A template allows a function or class to work with different data types without writing the same code multiple times.
Templates are also known as a form of generic programming.
Definition
A template is a mechanism in C++ that allows functions and classes to operate with different data types using a single definition.
Simple Example
Instead of writing separate functions:
int add(int a, int b); double add(double a, double b);
we can write one template:
template <typename T> T add(T a, T b) { return a + b; }
Types of Templates
C++ mainly provides two common types of templates:
- Function Template
- Class Template
1. Function Template
A function template allows a function to work with different data types.
Syntax
template <typename T> returnType functionName(T parameter) { // Function body }
T is a template type parameter.
Example of Function Template
#include <iostream> using namespace std; template <typename T> T add(T a, T b) { return a + b; } int main() { cout << "Integer: " << add(10, 20) << endl; cout << "Double: " << add(10.5, 20.5) << endl; return 0; }
Output
Integer: 30 Double: 31
The same add() function works with both int and double.
2. Function Template with Different Data Types
A function template can also accept different types.
Example
#include <iostream> using namespace std; template <typename T> void display(T value) { cout << "Value: " << value << endl; } int main() { display(100); display(10.5); display("Anuradha"); return 0; }
Output
Value: 100 Value: 10.5 Value: Anuradha
3. Function Template with Multiple Parameters
A template can have more than one type parameter.
Example
#include <iostream> using namespace std; template <typename T, typename U> void display(T a, U b) { cout << "First value: " << a << endl; cout << "Second value: " << b << endl; } int main() { display(10, 20.5); return 0; }
Output
First value: 10 Second value: 20.5
Here:
Trepresents the first data type.Urepresents the second data type.
4. Class Template
A class template allows a class to work with different data types.
Syntax
template <typename T> class ClassName { T data; };
Example of Class Template
#include <iostream> using namespace std; template <typename T> class Number { private: T value; public: Number(T v) { value = v; } void display() { cout << "Value = " << value << endl; } }; int main() { Number<int> n1(100); Number<double> n2(10.5); n1.display(); n2.display(); return 0; }
Output
Value = 100 Value = 10.5
5. Class Template with Multiple Types
A class template can have multiple type parameters.
Example
#include <iostream> using namespace std; template <typename T, typename U> class Data { private: T first; U second; public: Data(T a, U b) { first = a; second = b; } void display() { cout << "First: " << first << endl; cout << "Second: " << second << endl; } }; int main() { Data<int, double> d1(10, 20.5); d1.display(); return 0; }
Output
First: 10 Second: 20.5
6. Template with Multiple Parameters
Templates can contain multiple type parameters.
template <typename T, typename U, typename V> class Example { T a; U b; V c; };
For example:
Example<int, double, string> obj;
7. Non-Type Template Parameters
Templates can also accept values as parameters, not only data types.
Example
#include <iostream> using namespace std; template <typename T, int size> class Array { private: T data[size]; public: void displaySize() { cout << "Array size = " << size << endl; } }; int main() { Array<int, 5> a; a.displaySize(); return 0; }
Output
Array size = 5
Here:
Tis a type parameter.sizeis a non-type template parameter.
8. Template Function for Finding Maximum
Example
#include <iostream> using namespace std; template <typename T> T maximum(T a, T b) { return (a > b) ? a : b; } int main() { cout << "Maximum: " << maximum(10, 20) << endl; cout << "Maximum: " << maximum(15.5, 12.5) << endl; return 0; }
Output
Maximum: 20 Maximum: 15.5
9. Template Specialization
Sometimes a template needs a special implementation for a particular data type.
This is called template specialization.
Example
#include <iostream> using namespace std; template <typename T> class Display { public: void show(T value) { cout << "General value: " << value << endl; } }; template <> class Display<string> { public: void show(string value) { cout << "String value: " << value << endl; } }; int main() { Display<int> d1; Display<string> d2; d1.show(100); d2.show("Anuradha"); return 0; }
Output
General value: 100 String value: Anuradha
10. Advantages of Templates
1. Code Reusability
The same code can work with different data types.
2. Reduces Code Duplication
There is no need to write separate functions or classes for each data type.
3. Type Safety
Templates provide compile-time type checking.
4. Easy Maintenance
One template definition can be maintained instead of multiple similar implementations.
5. Generic Programming
Templates allow programmers to create general-purpose algorithms and data structures.
11. Disadvantages of Templates
1. Complex Error Messages
Template-related compiler errors can sometimes be difficult for beginners to understand.
2. Increased Compilation Time
Large or heavily used templates can increase compilation time.
3. Code Complexity
Advanced templates can make code difficult to understand.
4. Larger Generated Code
Different template instantiations can result in multiple generated versions of code.
12. Templates vs Function Overloading
| Templates | Function Overloading |
|---|---|
| Provides generic code for different types. | Provides multiple functions with the same name. |
| One template can handle many compatible types. | Each overload is explicitly written. |
| Useful for generic programming. | Useful when behavior or parameter lists differ. |
Example: template <typename T>. | Example: add(int,int) and add(double,double). |
13. Real-Life Example
Consider a sorting function.
Without templates, we might write separate functions:
sortInteger() sortDouble() sortFloat()
With templates, we can write one generic function:
template <typename T> void sort(T array[], int size) { // Sorting logic }
The same algorithm can then be used with different compatible types.
14. Templates and STL
The C++ Standard Template Library (STL) makes extensive use of templates.
Common STL components include:
vector list deque set map stack queue
For example:
#include <iostream> #include <vector> using namespace std; int main() { vector<int> numbers = {10, 20, 30}; for (int number : numbers) { cout << number << " "; } return 0; }
Output
10 20 30
vector<int> is a template specialization of the vector class for int.
Key Points
- Templates support generic programming in C++.
- They allow code to work with different data types.
typenameorclasscan be used to declare a type parameter.- Function templates create generic functions.
- Class templates create generic classes.
- Templates can have multiple parameters.
- Templates can also have non-type parameters.
- Template specialization provides a customized implementation for a particular type.
- STL containers heavily use templates.
Summary
Templates | ┌────────────┴────────────┐ ↓ ↓ Function Template Class Template | | ↓ ↓ Generic Functions Generic Classes | ↓ Different Data Types
Simple Definition
Template = A C++ feature that allows one function or class to work with different data types.