×

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

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

Palindrome Using While Loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Default arguments in C++

Arguments in a function are defined as the values supplied when the function is called. The source is the values supplied, and the destination is the receiving function. Let us...

3 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.