All About Templates in C++

All About Templates in C++

4 mins read551 Views Comment
Updated on Jan 16, 2023 18:12 IST

Generic programming is an approach where generic types are used as arguments in algorithms so that they can work for various data types.

2022_09_MicrosoftTeams-image-37-1.jpg

In this article, we will learn about an interesting feature of C++ used for generic programming – Templates. So, without further ado, let’s get started!

We will be covering the following sections today:

What are Templates in C++?

C++ Templates are basically a blueprint that determines how a generic class or function is created in C++. You can write a class or function that works with different data types with templates. 

Templates are a powerful C++ feature that allows you to build generic programs. There are two ways to implement templates as described below:

  • Function Template
  • Class Template
2022_09_templates-in-C.jpg

Explore free C++ courses

Recommended online courses

Best-suited C++ courses for you

Learn C++ with these high-rated online courses

– / –
4 months
β‚Ή4.24 K
6 weeks
– / –
15 days
– / –
– / –
– / –
70 hours
– / –
3 months
– / –
4 months
– / –
3 months
Free
3 weeks
Free
25 months

Function Template in C++

A standard C++ function works only with one set of data types. A C++ function template, however, is a single template that works with various data types simultaneously.

Defining a Function Template

A function template syntax is defined with the keyword template along with template argument(s) within angular brackets < >, which is followed by the function definition, as shown below:

 
template <typename T>
\n \n \n <typename t="">\n \n \n
\n \n \n
T functionName(T parameter1, T parameter2, ...) \n \n \n
{\n \n \n
// code\n \n \n
}\n \n \n
\n \n \n </typename t="">
Copy code

In the above-shown syntax, typename is the keyword, and T is the template argument that accepts multiple data types (int, float, etc.).

When we pass an argument of a particular data type to the function functionName(), the compiler generates a new version of functionName() for the given data type.

Calling Function Template

As soon as the function template is declared and defined, it can be called in other functions with the following syntax:

 
functionName
\n \n \n <datatype>\n \n \n
(parameter1, parameter2, ...); \n \n \n
\n \n \n </datatype>
Copy code

Let’s take a look at an example:

 
#include
\n \n \n <iostream>\n \n \n
\n \n \n
using namespace std;\n \n \n
\n \n \n
//Define a function template\n \n \n
template \n \n \n
\n \n \n <typename t="">\n \n \n
\n \n \n
T sum(T num1, T num2) {\n \n \n
return (num1 + num2);\n \n \n
}\n \n \n
\n \n \n
int main() {\n \n \n
\n \n \n
int res1;\n \n \n
double res2;\n \n \n
//Calling the function template\n \n \n
// with int parameters\n \n \n
res1 = sum\n \n \n
\n \n \n <int>\n \n \n
(6, 3);\n \n \n
cout << res1 << endl;\n \n \n
\n \n \n
//Calling the function template \n \n \n
// with double parameters\n \n \n
res2 = sum\n \n \n
\n \n \n <double>\n \n \n
(6.2, 1.3);\n \n \n
cout << res2 << endl;\n \n \n
\n \n \n
return 0;\n \n \n
} \n \n \n
\n \n \n </double>\n \n \n
\n \n \n </int>\n \n \n
\n \n \n
\n \n \n </typename t="">\n \n \n </iostream>
Copy code

Output:

 
9
7.5
Copy code

As it is visible in the above program, the function template adds two numbers. The function calls are based on the data types int and double. 

Understanding Function Overriding in C++
All About C++ Friend Function
Understanding Break Statement in C++

Class Template in C++

Class templates are similar to function templates and simultaneously work for different data types. Class templates define a family of classes in C++. 

Declaring a Class Template

A class template syntax also starts with the keyword template followed by template argument(s) within angular brackets < >, which is then followed by the class declaration, as shown below:

 
template
\n \n \n <class t="">\n \n \n
\n \n \n
class className {\n \n \n
private:\n \n \n
T var;\n \n \n
. . . \n \n \n
public:\n \n \n
T functionName(T parameter1, T parameter2, ...);\n \n \n
. . .\n \n \n
};\n \n \n
\n \n \n </class t="">
Copy code

In the above-shown syntax, class is the keyword, and T is the template argument that accepts multiple data types (int, float, etc.). Inside the body of the class, we declare a member variable var and a member function functionName(), both of type T.

Creating a Class Template Object

Once the class template is declared and defined, we can create its objects inside other classes or functions with the following syntax:

 
className
\n \n \n <datatype>\n \n \n
object; \n \n \n
\n \n \n </datatype>
Copy code

Let’s take a look at an example:

 
#include
\n \n \n <iostream>\n \n \n
\n \n \n
using namespace std;\n \n \n
\n \n \n
//Declaring class template\n \n \n
template \n \n \n
\n \n \n <class t="">\n \n \n
\n \n \n
class number {\n \n \n
private:\n \n \n
//Declare a variable of type T\n \n \n
T num;\n \n \n
\n \n \n
public:\n \n \n
number(T n) : num(n) {} //Constructor\n \n \n
\n \n \n
T get_num() {\n \n \n
return num;\n \n \n
}\n \n \n
};\n \n \n
\n \n \n
int main() {\n \n \n
\n \n \n
//Creating an object with int type\n \n \n
number\n \n \n
\n \n \n <int>\n \n \n
numberInt(8);\n \n \n
\n \n \n
//Creating an object with double type\n \n \n
number\n \n \n
\n \n \n <double>\n \n \n
numberDouble(2.7);\n \n \n
\n \n \n
cout << "int type number: " << numberInt.get_num() << endl;\n \n \n
cout << "double type number: " << numberDouble.get_num() << endl;\n \n \n
\n \n \n
return 0;\n \n \n
}\n \n \n
\n \n \n </double>\n \n \n
\n \n \n </int>\n \n \n
\n \n \n
\n \n \n </class t="">\n \n \n </iostream>
Copy code

Output:

 
int type number: 8
double type number: 2.7
Copy code

As it can be seen in the above program, we have implemented the class template by creating its objects numberInt(8) and numberDouble(2.7).

Class Template with Multiple Arguments

C++ also supports multiple and default template argument(s), as shown below:

 
template
class className {
private:
T var1;
U var2;
V var3;
. . .
public:
. . .
};
Copy code

Let’s take a look at an example:

 
#include
using namespace std;
//Declaring a class template with multiple and default parameters
template
class display {
private:
T var1;
U var2;
V var3;
public:
display(T v1, U v2, V v3) : var1(v1), var2(v2), var3(v3) {} //Constructor
void printVar() {
cout << "var1 = " << var1 << endl;
cout << "var2 = " << var2 << endl;
cout << "var3 = " << var3 << endl;
}
};
int main() {
//Creating an object with int, double and char types
display<int, double=""> obj1(5, 7.3, 'x');
cout << "obj1 values: " << endl;
obj1.printVar();
//Creating an object with int, double and bool types
display<double, char,="" bool=""> obj2(1.5, 'd', false);
cout << "\nobj2 values: " << endl;
obj2.printVar();
return 0;
}
</double,></int,>
Copy code

Output:

 
obj1 values:
var1 = 5
var2= 7.3
var3: x
obj2 values:
var1= 1.5
var2 = d
var3 = 0
Copy code

As you can see in above-given program, we have implemented the class template named display with multiple arguments, one of them being a default argument i.e., V whose default type is char.

Inside the class, we declare three variables var1, var2, and var3 where each corresponds to one of the template arguments. 

Function Overloading vs. Function Template in C++

Function Overloading Function Template
1. Function overloading is used when multiple functions perform similar operations. 1. A function template is used when multiple functions do identical operations.
2. Function overloading takes varying numbers of arguments. 2. Function templates cannot take varying numbers of arguments.

Advantages of Using Templates in C++

  • Templates are an effective way of generalizing APIs.
  • Templates and macros both are expanded at compile time. The former is considered an improvement because they are type-safe.
  • Using templates aids in avoiding common coding errors.

Disadvantages of Using Templates in C++

  • Creating a template can be a bit difficult for beginner coders.
  • When templates are used, the entire code is exposed.
  • Many compilers do not offer support for the nesting of templates.

 Endnotes

Hope this article helped you grasp the concept of templates in C++. Templates are a handy tool in C++ to reduce code lines and make our code more manageable. Explore our articles on the C++ to find out more about the language and consolidate your knowledge of the fundamentals. 

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio