Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: May 7, 2024
Difficulty: Easy

Template in C++

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Templates in C++ are like a set of instructions or a blueprint for creating similar things, like cookies from a cookie cutter. You can use the same template to make many cookies of the same shape and size, but you can use different ingredients to make different types of cookies. In the same way, you can use the same template in C++ to create many similar pieces of code but with different types of data.

Template in  C++

Also see, Literals in C, Fibonacci Series in C++

Templates in C++ are a way to create generic functions and classes that can work with any data type. They allow the programmer to write a single function or class that can be used with multiple data types without the need to write separate code for each type. Templates are defined using the keyword "template" and angle brackets (e.g., template <typename T>). The data type that the template will work with is specified as a parameter within the angle brackets.

Templates can be represented as:

template representation

The two main types of templates in C++:

  1. Class Templates
  2. Functions Templates

1. Class Templates in C++

A class template in C++ is similar to a function template, but it is used to create generic classes.

Syntax of Class Templates in C++

Here's a syntax of a template class:

template <typename T> 
class MyClass { 
// Class definition here
};

Example of Class Templates

  • C++

C++

#include <iostream>
#include <vector>
#include <utility>
using namespace std;

template <typename T, typename U>
class Map {
private:
   std::vector<std::pair<T, U>> data;
public:
   Map() {}
   void insert(T key, U value) { data.push_back(std::make_pair(key, value)); }
   U getValue(T key) {
       for (auto item : data) {
           if (item.first == key) {
               return item.second;
           }
       }
       return U();
   }
};

int main() {
   Map<int, string> myMap;
   myMap.insert(1, "apple");
   myMap.insert(2, "banana");
   myMap.insert(3, "mango");
   cout << myMap.getValue(3) << endl;
   return 0;
}

Explanation

  • A class template called "Map" that can store key-value pairs where the key is of type "T" and the value is of type "U". The template types can be replaced with any data type when an object of the class is created. 
     
  • The class has a private member variable called "data" which is a vector of pairs of type T and U.
     
  • It has a default constructor and two public member functions: insert() function to insert key-value pairs, getValue() function to retrieve the value associated with a specific key. 
     
  • In the main function, we create an object of the class with T=int, and U=string, insert some key-value pairs, retrieve the value associated with a key 2 and output it to the console.

Output

output

Class template with multiple parameters

It works similarly to class templates, but they define a single function instead of a class. The function can take multiple parameters, some or all of which can be template types. The function is then instantiated with specific types for the template parameters when it is called.

You can also use a template with multiple parameters like this:

template <typename T, typename U>
class MyClass {
 // Body
};
 
//OR
 
template <typename T, int N> 
class MyClass {
 // Body 
};

Non-Type Template Arguments

We may use non-type arguments as well as many arguments in the template. In addition to the type T parameter, we can utilize strings, function names, constant expressions, and built-in types as arguments. Consider the following example:

template<class T, int size>  
class array  
{  
       T arr[size];           // automatic array initialization.  
};  

In the above case, the nontype template argument is size and therefore, template supplies the size of the array as an argument.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Functions Templates in C++

 C++ template functions are a type of feature that allows the creation of generic functions. These functions can operate on multiple data types rather than being limited to a specific type. 

Syntax of Functions Templates in C++

Syntax of a c++ template function:

template <typename T> 
T findMax(T arr[], int size) {
 // Function definition here 
};


In both examples, the "typename T" is the template parameter. It can be named anything, but "T" is a common convention. When the template is instantiated, the type passed as the template argument will replace T.

Example of Function Templates

  • C++

C++

#include <iostream>
using namespace std;

template <typename T>
void printArray(T* arr, int size) {
   for (int i = 0; i < size; i++) {
       cout << arr[i] << " ";
   }
   cout << endl;
}

int main() {
   int arr[] = {1, 2, 3, 4, 5};
   printArray(arr, 5);
   //float arr[] = {1.2, 2.3, 3.4, 4.5, 5.6};
   //printArray(arr, 5);
   return 0;
}

Explanation

In the main function, an array of integers is declared and initialized with values {1, 2, 3, 4, 5}. The printArray function is then called, passing the array and its size as arguments. This will print out each element of the array on a separate line.

You can also use this function template with other types, such as float, double, string, etc.

Output

Output


For float datatype,
 

Output

Example of Function Templates with Multiple Parameters

  • C++

C++

#include <iostream>
using namespace std;

template <typename T, typename U>
void printValues(T value1, U value2) {
   cout << value1 << ", " << value2 << endl;
}

int main() {
   printValues<int, string>(5, "hello");
   printValues<double, char> (3.14, 'x');
   return 0;
}

Explanation

The above code will define a function template that takes two template parameters, T and U, and prints out the values of two parameters passed to it. In the main function, the function template is instantiated with different types for T and U and passed with different values, and it will print out the values.

Output

output

Overloading a Function Template in C++

We can overload the generic function, which means that the argument list of the overloaded template functions can differ. Let's understand this through a simple example:

  • C++

C++

#include <iostream>  
using namespace std;
template<class X> void fun(X a)
{
std::cout << "Value of a is : " <<a<< std::endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
std::cout << "Value of b is : " <<b<< std::endl;
std::cout << "Value of c is : " <<c<< std::endl;
}
int main()
{
fun(30);
fun(50,20.5);
return 0;
}

Output:

Overloading a Function Template

In the above example, the template of fun() function is overloaded.

Restrictions of Generic Functions

Except for the data type, generic functions do the identical operation in all variants of a function. Let's look at a basic example of an overloaded function that cannot be substituted by a generic function because the functions have different functions.

  • C++

C++

#include <iostream>  
using namespace std;
void fun(double var1)
{
cout<<"value of a is : "<<var1<<'\n';
}

void fun(int var2)
{
if(var2%2==0)
{
cout<<"Number is even";
}
else
{
cout<<"Number is odd";
}

}

int main()
{
fun(4.6);
fun(6);
return 0;
}

Output:

Restrictions of Generic Functions

The ordinary functions are overloaded in the above example. We cannot overload the generic functions because they serve distinct purposes. The first displays the value, and the second decides if the number is even or odd.

Advantages of Using Templates in C++

When we use the template in C++, it provides several advantages:

  • It enables code reuse by allowing the definition of generic algorithms or data structures that can operate on different data types. 
     
  • It supports generic programming, where algorithms and data structures can be designed without specifying concrete types. 
     
  • It can ensure type safety at compile-time. 
     
  • It can facilitate the generation of optimized code specific to each data type. 
     
  • The C++ Standard Library extensively uses templates to provide a wide range of generic algorithms, containers, and data structures. 
     
  • It allows customization through template arguments. 

Template Argument Deduction

Template argument deduction in C++ refers to the process by which the compiler determines the template arguments for a function or class template based on the arguments passed to it. When a function template is called without explicitly specifying template arguments, the compiler deduces the template arguments by analyzing the types of the function arguments.

For example:

template<typename T>
void print(T value) {
    std::cout << value << std::endl;
}

int main() {
    print(5); // Deduces T as int
    print("Hello"); // Deduces T as const char*
    return 0;
}

In this example, the compiler deduces the template argument T as int for the first function call and as const char* for the second function call.

Difference between Function Overloading and Templates in C++

Function overloading in C++ allows multiple functions with the same name but different parameters to coexist. Each overloaded function has a distinct signature based on the number or types of its parameters.

On the other hand, templates in C++ provide a mechanism for generic programming by allowing the creation of functions or classes that operate on generic types. Templates allow you to define a single function or class template that can work with different data types without needing to write separate implementations for each type.

The key difference between function overloading and templates is that function overloading is based on the signatures of functions, while templates are based on generic programming principles and operate on types rather than specific function signatures. Additionally, templates offer more flexibility and reusability by allowing the creation of generic code that can work with a wide range of data types.

Frequently Asked Questions

What is class template in C++ with example?

A class template is a blueprint for generating generic classes that can work with multiple data types. For example, we create a PairValue is a class template that represents a pair of values. By using the class template, we can create pairs of different types (int and double in this case) without duplicating the class definition.

What is the difference between template and function in C++?

Templates enable generic programming by allowing the creation of generic algorithms or data structures that can operate on multiple data types. On the other hand, functions define a specific behavior or operation that operates on specific input values or types. 

What is the difference between template and macro in C++?

The main distinction between templates and macros is the type of operations that they automate. Macros automate repetitive operations within an existing document or application, whereas templates automate the process of creating a new document.

What happens when there is a static member in a template class/function? 

When there is a static member in a template class or function, each instantiation of the template shares the same static member. This means that the static member is shared across all instances of the template, regardless of the template arguments used for instantiation.

Read Also -  Difference between argument and parameter

Conclusion

To summarise the article, we have thoroughly discussed the C++ template function. We learned that there are two ways to represent C++ template function: class template and function template.

For more articles like the  C++ template function, you can look at the following:


Do visit our website to read more such blogs. Make sure you enroll in our courses. You can take mock testssolve problems, and interview puzzles. Also, you can check out some exciting interview stuff- interview experiences and an interview bundle for placement preparations. 

Happy Coding!

Topics covered
1.
Introduction
2.
1. Class Templates in C++
2.1.
Syntax of Class Templates in C++
2.2.
Example of Class Templates
2.3.
C++
2.4.
Class template with multiple parameters
2.5.
Non-Type Template Arguments
3.
Functions Templates in C++
3.1.
Syntax of Functions Templates in C++
3.2.
Example of Function Templates
3.3.
C++
3.4.
Example of Function Templates with Multiple Parameters
3.5.
C++
3.6.
Overloading a Function Template in C++
3.7.
C++
3.8.
Restrictions of Generic Functions
3.9.
C++
4.
Advantages of Using Templates in C++
5.
Template Argument Deduction
6.
Difference between Function Overloading and Templates in C++
7.
Frequently Asked Questions
7.1.
What is class template in C++ with example?
7.2.
What is the difference between template and function in C++?
7.3.
What is the difference between template and macro in C++?
7.4.
What happens when there is a static member in a template class/function? 
8.
Conclusion