In C++, a template is a mechanism that allows you to define generic classes or functions. Templates are used to create reusable code that can work with different data types without sacrificing type safety. They provide a way to write algorithms and data structures that can be customized to work with various types, allowing for code reusability and flexibility.
There are two main types of templates in C++:
- Function Templates: Function templates allow you to define a generic function that can operate on different data types. Instead of writing multiple functions for each specific data type, you can define a single function template that can be instantiated for different types. The template parameters are used to represent the generic types. When the template is instantiated with a specific type, the compiler generates the appropriate function code.
 
Here’s an example of a function template that swaps two values:
<span class="hljs-keyword">template</span> <<span class="hljs-keyword">typename</span> T>
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">swap</span><span class="hljs-params">(T& a, T& b)</span> </span>{
    T temp = a;
    a = b;
    b = temp;
}
The typename T here is the template parameter, which represents a generic type. It can be replaced with any valid C++ type when the template is used.
- Class Templates: Class templates allow you to define generic classes that can work with different types. Similar to function templates, class templates use template parameters to represent generic types. The template parameters can be used as types for member variables, member functions, and method arguments within the class template definition.
 
Here’s an example of a class template that represents a generic stack:
<span class="hljs-keyword">template</span> <<span class="hljs-keyword">typename</span> T>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Stack</span> {
<span class="hljs-keyword">private</span>:
    T* elements;
    <span class="hljs-type">int</span> size;
<span class="hljs-keyword">public</span>:
    <span class="hljs-comment">// Constructor, destructor, and other member functions...</span>
    <span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">push</span><span class="hljs-params">(T item)</span></span>;
    <span class="hljs-function">T <span class="hljs-title">pop</span><span class="hljs-params">()</span></span>;
};
In this example, T is the template parameter representing the generic type of elements in the stack. The Stack class template can be instantiated with different types, such as int, double, or any other valid C++ type.
Templates allow you to write code that is flexible and reusable across different types, enabling generic programming in C++. They are an essential feature for creating container classes, algorithms, and other components that need to work with different data types while maintaining type safety.
