×

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using generic parameters.

There are commonly two ways to represent templates:

  1. Function Templates
  2. Class Templates

Let’s discuss these two representations in detail.

Functional Templates

Functional templates usually define a template for a function. If we take into account a function multiply(), we can use it with any data type like int, char, float, or double type values. Consider the below characteristics of functional templates.

  1. Functional templates are extensively used in generic functions like add() or delete(). These generic functions define some sort of operations that can be easily applied to different data types.
  • The operation of the function depends on the type of data passed as a parameter. Consider quick sort algorithm, which uses general function methodology with arrays and strings.
  • The template keyword helps in the creation of a generic function. The template defines what function will serve.

Syntax:      

 template < class Ttype>
 return_type_function_name(parameter_list) 
 { 
 // body of function. 
 }  

Here,

Ttype: It is a placeholder name that is later replaced by the compiler by the actual data type.

class: It is a keyword used to generic template declaration.

Example Code:

 #include<bits/stdc++.h>
 using namespace std;
 template<class A> A multiply(A &x,A &y) 
 { 
     A result = x*y; 
     return result; 
 } 
 int main() 
 {
   int i =4; 
   int j =5; 
   float m = 3.3; 
   float n = 4.4; 
   cout<<"Mulplication of x and y is :"<<multiply(i,j);
   cout<<'\n'; 
   cout<<"Mulplication of x and y is :"<<multiply(m,n); 
   return 0; 
 } 

Output:

C++ Templates

Explanation:

In the above code, we have a placeholder value A associated with function multiplication which takes two parameters, x, and y. Another variable, 'result' is assigned with placeholder A, which stores the multiplicative value of x and y. We must set some random integer and float values to variables I, j, m, and n, respectively. The output of the code is the multiplicative value of these variables.

Similarly, functional templates can also be used with multiple parameters by separating with commas in the list.

Also, they can be easily overloaded, which is restricted to some extent depending on the situation.

Class Templates

A class template in C++ is used for specification for generating classes based on parameters. Generally, they are used to implement containers. A given set of types is passed as template arguments in a class template.

Syntax:   

 template<class T1, class T2, ......>  
 class class_name 
 { 
 // Body of the class. 
 }  

Let us discuss class templates with the help of a coding example.

 #include<bits/stdc++.h>
 using namespace std;
 template <class X>
 class Calculator_Sample
 {
 private:
                 X number1, number2;
 public:
                 Calculator_Sample(X a1, X a2)
  {
                                 number1 = a1;
                                 number2 = a2;
                 }
                 void Result()
    {
                                 cout << "Your entered : " << number1 << " and " << number2 << "." << endl;
                                 cout << "Addition Result: " << add() << endl;
                                 cout << "Subtraction Result: " << subtract() << endl;
                                 cout << "Product Result: " << multiply() << endl;
                                 cout << "Division Result: " << divide() << endl;
   }
                 X add() { return number1 + number2; }
                 X subtract() { return number1 - number2; }
                 X multiply() { return number1 * number2; }
                 X divide() { return number1 / number2; }
 };
 int main()
 {
                 Calculator_Sample<int> intCalc(3, 4);
                 Calculator_Sample<float> floatCalc(12.4, 11.2);
                 cout << "Results in integers :" << endl;
                 intCalc.Result();
                 cout << endl << "Results in float :" << endl;
                 floatCalc.Result();
                 return 0;
 }  

Output:

C++ Templates

Explanation:

In the above program, a class template Calculator_sample is declared. The class template X contains two private members of X, namely number1 and number2, and a constructor to initialize the members.

To calculate addition, subtraction, multiplication, and division, it also contains public members who return the data type defined by the user. Likewise, to display the final output, we declared a function Result().

In the driver code, we created two objects of the class namely floatCalc and intCalc which are based on integer and float data types, and the values are initialized with the help of the constructor.

We used <int> and <float> to tell the compiler the data type we are using for the creation of the class. By doing this, it creates a class definition that can later be used accordingly.

The Result() function performs the operations of the class Calculator_sample and displays the values on the console as defined in the code.

Key Points:

Let’s consider some key points, which are listed below:

  1. C++ holds its back by supporting a powerful feature used for generic programming implementation popularly known as template.
  • With the help of a template, we can easily create a family of classes or functions that can handle different data types.
  • Faster and easier development is achieved by using templates because we can easily handle class and function redundancy.
  • Class template and function template can be used for multiple parameters.
  • Overloading can be easily done in a function template.
  • We can use built-in derived data type or non-type arguments with the help of templates in C++.

Related Topics

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

Advanced C++ with Boost Library

The goal of the Boost Libraries is to be widely applicable and used in a variety of applications. For instance, they can in handy when working with huge numbers whose...

4 minutes read.

Delete Operator in C++

Overview We can reserve allocation for a variable or an array at runtime in C++. Dynamic memory allocation is the term for this. After utilising a variable in C++, we must...

4 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.