What is Template in C++: Simple Explanation and Example
template is a tool that lets you write code that works with any data type without repeating it. It acts like a blueprint for functions or classes, allowing you to create flexible and reusable code that adapts to different types automatically.How It Works
Think of a template in C++ like a cookie cutter. Instead of baking one cookie at a time, you create a shape that can cut many cookies of different flavors but the same shape. Similarly, a template lets you write one function or class that can work with many types of data, such as numbers, letters, or custom objects.
When you use a template, the compiler makes a specific version of your function or class for the type you want. This means you don't have to write the same code again and again for different types. Templates save time and reduce mistakes by reusing the same logic for many data types.
Example
This example shows a simple template function that adds two values of any type and returns the result.
#include <iostream>
#include <string>
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
std::cout << add(5, 3) << "\n"; // Works with integers
std::cout << add(2.5, 4.1) << "\n"; // Works with doubles
std::cout << add(std::string("Hi, "), std::string("there!")) << "\n"; // Works with strings
return 0;
}When to Use
Use templates when you want to write code that works with many types without copying and changing it for each type. For example, if you want a function to sort numbers, letters, or custom objects, a template lets you write one sorting function that works for all.
Templates are common in libraries and frameworks where flexibility and reuse are important. They help keep code clean, reduce errors, and make maintenance easier.
Key Points
- Templates let you write generic code that works with any data type.
- The compiler creates specific versions of templates for each type you use.
- Templates reduce code duplication and improve code reuse.
- They are useful for functions and classes that need to handle multiple types.