A C++ template is a robust addition to the C++ language, enabling the creation of generic classes and functions. This capability supports generic programming, a method that leverages generic types as inputs in algorithms to make them applicable to various data types.
Types of Templates
There are mainly two types of Templates in C++.
Now, we will discuss these templates one by one.
1) Function Template
In C++, a function template allows developers to create versatile functions that work with diverse data types. These generic functions establish a collection of actions that are compatible with a range of data types.
The data type utilized in the function is decided during compile-time, influencing the function call based on the data type. For instance, the Quick Sort algorithm could be implemented through a function template, allowing the sorting function to operate with various arrays like integers, doubles, floats, and other data types.
A universal function can be generated with the keyword template. This specific term establishes a template parameter that serves as a substitute for a data type.
Syntax of Function Template
It has the following syntax:
template < class Ttype>
ret_type func_name(parameter_list)
{
// body of function.
}
In this format,
- Ttype: Serves as a placeholder title for a data type employed by the function within its definition. This placeholder will be substituted by the compiler with the real data type automatically.
- class: The class term is utilized to indicate a generic type in a template statement.
C++ Function Template Example
Let's consider an instance to demonstrate the function template in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;
}
int main() //Main Function
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is : "<<add(i, j);
cout<<'\n';
cout<<"Addition of m and n is : "<<add(m, n);
return 0;
}
Output:
Addition of i and j is : 5
Addition of m and n is : 3.5
Explanation:
In the previously mentioned example, we have generated a function template capable of executing the addition operation on various data types such as integer, float, or double.
Function Templates with Multiple Parameters
In C++, we can incorporate various generic types within the template function by separating them with commas.
Syntax
It has the following syntax:
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
In this particular syntax, it has been observed that the template function has the ability to receive varying quantities of arguments belonging to diverse types.
In this example, we will explore how to work with C++ function templates that have multiple parameters.
template < class Ttype>
ret_type func_name(parameter_list)
{
// body of function.
}
#include <iostream>
using namespace std;
template <class T, class U>
T add(T a, U b) {
return a + b;
}
int main() {
cout << add(5, 3.2) << endl;
cout << add(10.5, 20) << endl;
cout << add(2.5, 3.5) << endl;
return 0;
}
In this code snippet, the add function template is defined with two template parameters T and U. This function takes two parameters of type T and U, and it returns the sum of these two parameters.
Inside the main function, we demonstrate how to use the add function template with different types of parameters. The output will display the results of adding integers with floating-point numbers and floating-point numbers with other floating-point numbers.
Let's consider a scenario to demonstrate the function template with several parameters in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
template<class X,class Y>
void fun(X a,Y b)
{
cout << "Value of a is: " <<a<< endl;
cout << "Value of b is: " <<b<< endl;
}
int main() //main function
{
fun(15,12.3);
return 0;
}/textarea></div>
<a class="btn btn-apna" href="https://www.cpptutorial.com/cpp/tryit?program=cpp-templates2" target="_blank">Compile and Run</a></div>
<p><strong>Output:</strong></p>
<div class="codeblock3">
<pre>Value of a is: 15
Value of b is: 12.3
</pre>
</div>
<p><strong>Explanation:</strong></p>
<p>In this example, we have taken a function template with two generic types, X and Y, which allows the fun() function to accept arguments of different data types. When the fun(15, 12.3) is invoked, the compiler automatically generates a version of the function where X is int and Y is double, and it displays both values.</p>
<h3 class="h3">Function Overloading with Template</h3>
<p>In C++, we can overload the generic function. It means that the overloaded template functions can differ in the parameter list.</p>
<p><strong>C++ Overloading a Function Template Example</strong></p>
<p>Let us take an example to illustrate the overloading a function template in C++.</p>
<div class="codewrapper">
<h3 class="h3">Example</h3>
<div class="codeblock"><textarea class="cpp" name="code">#include <iostream>
using namespace std; //using standard namespace
template<class X>
void fun(X a)
{
cout << "Value of a is : " <<a<< endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
cout << "Value of b is : " <<b<< endl;
cout << "Value of c is : " <<c<< endl;
}
int main() //main function
{
fun(10);
fun(20,30.5);
return 0;
}
Output:
Value of a is : 10
Value of b is : 20
Value of c is : 30.5
Explanation:
In the scenario described, the fun function template is overloaded to define two variations of the function. The initial version takes one generic parameter, while the other version accepts two generic parameters that could be of different types. Upon invoking fun(10), the single-parameter variant is executed, and when fun(20, 30.5) is invoked, the two-parameter variant is utilized.
Restrictions of Function Templates
In C++, function templates are unable to execute identical operations across all function variants, particularly when there are variations in functionality.
C++ Example of Restrictions of Function Template
Let's consider an example to demonstrate the limitations of function templates in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
void fun(double a)
{
cout<<"value of a is : "<<a<<'\n';
}
void fun(int b)
{
if(b%2==0)
{
cout<<"Number is even";
}
else
{
cout<<"Number is odd";
}
}
int main() //main function
{
fun(4.6);
fun(6);
return 0;
}
Output:
value of a is : 4.6
Number is even
Explanation:
In this instance, we are demonstrating the concept of function overloading with regular functions. It's important to note that overloading cannot be applied to generic functions due to their distinct functionalities. The initial function is responsible for showcasing the value, while the subsequent one assesses if the number is even.
2) Class Template
In C++, the class template can be declared in a similar manner as the function template. If a class incorporates templates, it is referred to as a generic class.
We have the ability to establish a blueprint for a class. For instance, a template class can be generated for the array class to handle arrays of different types like integer arrays, decimal arrays, and floating-point arrays.
Syntax
template<class Ttype>
class class_name
{
.
.
}
In this structure,
- Ttype: Serves as a temporary label that gets assigned when the class is created. Various generic data types can be specified by separating them with commas. The Ttype is accessible within the class definition.
Now, we create an instance of a class
class_name<type> ob;
Where,
- class_name: It represents the name of the class.
- type: It represents the data type that the class is operating on.
- ob: It represents the name of the object.
C++ Class Template Example
Let's consider an instance to demonstrate the class template in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
cout << "Addition of num1 and num2 : " << num1+num2<<endl;
}
};
int main() //main function
{
A<int> d;
d.add();
return 0;
}
Output:
Addition of num1 and num2 : 11
Explanation:
In this instance, we establish a blueprint for class A. Within the main function, we instantiate an object of class A referred to as 'd'.
Class Template with Multiple Parameters
In C++, it is possible to incorporate numerous generic data types within a class template, with each type being distinctly separated by a comma.
Syntax
It has the following syntax:
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
A C++ class template example showcasing the utilization of multiple parameters is demonstrated below:
template <class T, class U>
class Pair {
T first;
U second;
public:
Pair(T a, U b) : first(a), second(b) {}
T getKey() { return first; }
U getValue() { return second; }
};
int main() {
Pair<int, double> pair1(1, 3.14);
Pair<std::string, bool> pair2("hello", true);
std::cout << "Pair 1: " << pair1.getKey() << " - " << pair1.getValue() << std::endl;
std::cout << "Pair 2: " << pair2.getKey() << " - " << pair2.getValue() << std::endl;
return 0;
}
Let's consider a basic scenario where a class template includes a pair of generic data types.
Example
#include <iostream>
using namespace std; //using standard namespace
template<class T1, class T2>
class A
{
T1 a;
T2 b;
public:
A(T1 x,T2 y)
{
a = x;
b = y;
}
void display()
{
cout << "Values of a and b are : " << a<<" ,"<<b<<endl;
}
};
int main() //main function
{
A<int,float> d(5,6.5);
d.display();
return 0;
}
Output:
Values of a and b are : 5,6.5
Explanation:
In this illustration, a class template is presented featuring a pair of type parameters (T1 and T2), enabling the creation of class instances with varied data types. Subsequently, class A is designed to retain and exhibit two values corresponding to types T1 and T2. Within the main function, an object labeled d of class A<int, float> is instantiated, assigned the values 5 and 6.5, and then the display method is called to showcase these assigned values.
Non-type Template Arguments
In C++, the template is capable of accommodating multiple parameters, including non-type arguments. Apart from the type T parameter, various other argument types like strings, function identifiers, constant expressions, and primitive types can also be utilized.
Syntax
It has the following syntax:
template<class T, int size>
class array
{
T arr[size]; // automatic array initialization.
};
In this scenario, the non-type template parameter is the size, so templates provide the array size as an argument.
Parameters are defined during the instantiation of class instances:
array<int, 15> t1; // array of 15 integers.
array<float, 10> t2; // array of 10 floats.
array<char, 4> t3; // array of 4 chars.
C++ Non-type Template Arguments Example
Let's consider a scenario to demonstrate the non-type template parameter in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
template<class T, int size>
class A
{
public:
T arr[size];
void insert()
{
int i =1;
for (int j=0;j<size;j++)
{
arr[j] = i;
i++;
}
}
void display()
{
for(int i=0;i<size;i++)
{
std::cout << arr[i] << " ";
}
}
};
int main() //Main Function
{
A<int,10> t1;
t1.insert();
t1.display();
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
Explanation:
In this instance, a class template is established that includes a nontype template parameter, namely, size. This parameter is defined during the instantiation of the 'A' class object.
Difference between Function Overloading and Function Templates
Some variances between function overloading and function templates in C++ are outlined below:
| Features | Function Overloading | Function Templates |
|---|---|---|
| Purpose | Function overloading defines multiple functions with the same name but different arguments. | It allows us to write generic functions that operate with any data type. |
| Flexibility | It has limited flexibility to explicitly defined overloads. | It is more flexible for generic programming. |
| Syntax | It defines multiple functions with the same name but different arguments. | It uses template_PRESERVE21__ and some other similar template declarations. |
| Code Duplication | It needs to manually write each function version. | It helps to reduce code duplication. |
| Maintenance | It is harder to maintain. | It is easy to maintain. |
C++ Template MCQs
1) Which of the following options is used for generic programming?
- Modules
- Templates
- Abstract Classes
- Virtual Functions
2) Which of the following options shows the correct syntax of function templates?
- template<typename T> returnType functionName(T arg)
- template<class T> returnType functionName(T arg)
- template<T> returnType functionName(T arg)
- Both A and B
3) Which of the following options is correct about class templates in C++?
- They cannot have member functions
- They must be instantiated with specific types before use
- They can only accept one type parameter
- They are slower than regular classes
b) Prior to utilization, they need to be instantiated with particular types.
4) What will be the output of the following code?
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class X, class Y>
class cpptutorial
{
X a;
Y b;
};
int main()
{
cpptutorial<char, char> c;
cpptutorial<int, int> d;
cout << sizeof(c) << endl;
cout << sizeof(d) << endl;
return 0;
}
5) Is it possible to make use of multiple-type parameters in a template?
- This feature is exclusive to function templates.
- This functionality is restricted to class templates.