Browse by Domains

Templates in C++ With Examples | 2024

Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Generic Programming is an approach to programming where generic types are used as parameters in algorithms to work for a variety of data types.In C++, a template is a straightforward yet effective tool. To avoid having to write the same code for many data types, the simple concept is to pass the data type as a parameter. 

Special functions that can interact with generic types are known as function templates. As a result, we can develop a function template whose functionality can be applied to multiple types or classes without having to duplicate the full code for each kind.

This may be done in C++ by using template parameters. Similar to how standard function parameters may be used to send values to a function, template parameters allow you to pass types to a function as well. A template parameter is a specific form of the parameter that can be used to pass a type as an argument. These parameters can be used by these function templates just like any other ordinary type.

So, this blog is here to help you out in understanding the details of templates in c++, how they work, templates specialization, templates library and many more. Read on to know more!

Table of Contents 

  1. What is Templates in C++?
  2. How do templates work in C++?
  3. Types of Templates in C++
  4. Difference between function overloading and templates in C++?
  5. Advantages of Using Templates in C++
  6. Disadvantages of Using Templates in C++
  7. Overloading of Template Function
  8. What is Templates Specialization? 
  9. Function Specialization
  10. Class Specialization
  11. Template Parameter
  12. Standard Template Library in C++

What is Templates in C++?

Templates in C++ is an interesting feature that is used for generic programming and templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Simply put, you can create a single function or single class to work with different data types using templates. 

C++ template is also known as generic functions or classes which is a very powerful feature in C++. A keyword “template” in c++ is used for the template’s syntax and angled bracket in a parameter (t), which defines the data type variable.

How do templates work in C++?

Templates in c++ works in such a way that it gets expanded at compiler time, just like macros and allows a function or class to work on different data types without being rewritten.

Types of Templates in C++

There are two types of templates in C++

  • Function template
  • Class templates
Types of Templates in C++

What is the function template in C++?

A function template in c++ is a single function template that works with multiple data types simultaneously, but a standard function works only with one set of data types.

C++ Function Template Syntax

template<class type>ret-type func-name(parameter list)
{
//body of the function
}

Here, type is a placeholder name for a data type used by the function. It is used within the function definition.

The class keyword is used to specify a generic type in a template declaration.

C++ function template example:

Source Code:

#include<iostream.h>
using namespace std;
template<classX>//can replace 'class" keyword by "typename" keyword
X func( Xa,Xb)
{
return a;
}
int main()
count<<func(15,8),,endl;//func(int,int);
count,,func('p','q'),,endl;//func(char,char);
count<<func(7.5,9.2),,endl;//func(double,double)
return();
}
Output 
15
p
7.5

Defining a Class Member Outside the Class Template

You’ve seen how a member function is defined within a class template. Now, alternatively, it is also possible for the template member function to be defined independently of the declaration of its class template.

The compiler will use the template arguments that you used, in this case, to create the class template when you call a member function of a class template specialization. The following illustration exemplifies this:

Example:

#include<iostream>
using namespace std;
    template<class A> class B {
   public:
      A operator+(A);
};

template<class A> A B<A>::operator+(A x) {
   return x;
};

int main() {
   B<char> ob1;
   B<int> ob2;
   cout<< ob1 +'p' << endl;
   cout<< ob2 + 10;
   return 0;
}
Output:
P
10

A definition of the overloaded addition operator is given outside of class A. It is equal to the statement ob1.operator+(‘p’) rather than ob1+ “p”. “ob2 + 10” is similar to “ob2.operator+” (10).

Simple Calculator Using Class Templates

We can make a simple Calculator performing the four basic arithmetic operations in C++ using a class template. The template of the class will consist of two variables whose values are passed at the time of object creation. The constructor of this class takes two arguments of generic datatypes. Further, you will see, this Calculator class template consists of five main functions – show(), addition(), subtraction(), multiplication(), and division().  The show() function is responsible for calling the rest of the four generic functions. Moving ahead, we have created two instances from the template of Calculator class and performed the basic calculations using its class functions. 

Example:

template <class Temp>
class Calculator
{
private:
        Temp n1, n2;
        
public:
        Calculator(Temp num1, Temp num2)
        {
                n1 = num1;
                n2 = num2;
        }
        
        void show()
        {
                cout << "Addition is: " << n1 << "+" << n2 << "=" << addition() << endl;
                cout << "Subtraction is: " <<n1 << "-" << n2 << "=" << subtraction() << endl;
                cout << "Product is: " << n1 << "*" << n2 << "=" << multiplication() << endl;
                cout << "Division is: " << n1 << "/" << n2 << "=" << division() << endl;
        }
        
        Temp addition() { return (n1 + n2); }
        
        Temp subtraction() { return n1 - n2; }
        
        Temp multiplication() { return n1 * n2; }
        
        Temp division() { return n1 / n2; }
};

int main()
{
 Calculator<int> Calc1(25, 12);
        Calculator<float> Calc2(13.6, 5.9);
        
        cout << "Integer results for 25 and 12:" << endl;
        Calc1.show();
        
        cout << endl << "Float results for 13.6 and 5.9:" << endl;
        Calc2.show();
        
        return 0;
}

Output

C++ Class Templates With Multiple Parameters

 It is possible to provide more than one type when generating templates. A class template can have many generic data types. They are listed in a comma-delimited format as shown in the following example.

Example:

#include<iostream>
using namespace std;

// Class template with more than one parameter
template<class Temp1, class Temp2>
class Sample
{
		Temp1 l;
		Temp2 m;
	public:
		Sample(Temp1 a, Temp2 b)
		{
			l = a;
			m = b;
		}
		void display()
		{
			cout << "The inputs are: " <<l << " and " << m << endl;
		}
};

// Driver function
int main()
{
	// instantiation
	Sample <int, char> ob1 (24, 'A');
	
	// instantiation 
	Sample<int, float> ob2(22.56, 34.9);
	
	//Calling the display function to see the output
             ob1.display();
	ob2.display();
	
	return 0;
}

Output:


As seen in the above cited example, we can use more than one parameter for a template in C++. Here, the template Temp takes two parameters, both of the Sample class type, separated by a comma. Moreover, the constructor of the Sample class takes two arguments of generic datatype. When we create objects, the types of arguments are specified in angular brackets (< >). In case of multiple parameters, the datatypes are also separated by commas. The constructor is called at the time when objects are created, and template arguments receive values.

What is class template in c++?

The class template in c++ is like function templates. They are known as generic templates. They define a family of classes in C++. 

Syntax of Class Template

template<class Ttype>
class class_name
{
//class body;
}

Here Type is a placeholder type name, which will be specified when a class instantiated.

The Type can be used inside the body of the class.   

Class template in c++ example:

Source Code:

#include<iostream.h>
using namespace std;
template <class C>
class A{
private;
C,a,b;
public:
A(Cx,Cy){
a=x;
b=y;
}
void show()
}
count<<"The Addition of"<<a<<"and"<<b<<"is"<<add()<<endl;
}
C add(){
C c=a+b;
return c;
}
};
int main(){
Aaddint(8,6);
Aaddfloat(3.5,2.6);
Aaaddouble(2.156,5.234);
Aaddint.show();
cout<<endl;
adddouble.show();
count<<endl;
return 0;
}

Output
The addition of 8 and 6 is 14 
Addition of 3.5 and 2.6 is 6.1
The addition of 2.156 and 5.234 is 7.390

Difference between function overloading and templates in C++?

Function overloadingFunction Template
This is used when multiple functions do similar operations.This is used when functions do identical operations.
Function overloading can take varying numbers of arguments.Templates cannot take varying numbers of arguments.

Advantages of Using Templates in C++

  • Templates are type-safe.
  • They are generally considered as an improvement over macros for these purposes.
  • Templates avoid some common errors found in code that make heavy use of function-like macros.
  • Both templates and macros are expanded at compile time.
  • They are a good way of making generalisations for APIs.

Disadvantages of Using Templates in C++

  • Many compilers do not support nesting of templates.
  • When templates are used, all codes exposed.
  •  Some compilers have poor support of templates.
  • Approx all compilers produce unhelpful, confusing error messages when errors are detected in the template code.
  • It can make it challenging to develop the template.

Overloading of C++ template

  • A template function is called that could be created with an exact match.
  • Call an ordinary function that has an exact match.

What is Templates Specialization? 

Templates Specialization is defined as a mechanism that allows any programmer to use types as parameters for a class or a function.  A function/class defined using the template is called a generic function/class, and the ability to use and create generic functions/classes is one of the critical features of C++.

//A generic sort function
template<class X>
{
//code to implement quick sort
}
//Template specilization:A function
//specialized for char data type
template<>
void sort<char>(char arr[],int size)
{
//code to impletement counting sort
}

Function Specialization

We have the add() function, which takes two parameters and returns the same type of data after adding the two args.

Function specialization example:  

Source Code:

#include <iostream.h>
using namespace std ;

//max returns the maximum of the two elements of type T, where T is a
//class or data type for which operator> is defined.
template <class T>
T max(T a, T b)
{
    return a > b ? a : b ;
}

int main()
{    
    cout << "max(80, 95) = " << max(10, 15) << endl ;
    cout << "max('a', 'z') = " << max('k', 's') << endl ;
    cout << "max(11.1, 18.2) = " << max(11.1, 18.2) << endl ;
    cout << "max(\"Ahil\", \"Riya\") = " << max("Ahil", "Riya") << endl ;
    return 0 ;
}
Output
max(80, 95) = 95
max('a', 'z') = z
max(11.1, 18.2) = 18.2
max("Ahil", "Riya") = Riya

 Class Specialization

Class specialization example:   

Source Code:

#include <iostream> 
using namespace std; 
  
template <class T> 
class Test 
{ 
  // Data memnbers of test 
public: 
   Test() 
   { 
       // Initialization of data members 
       cout << "General template  \n"; 
   } 
   // Other methods of Test 
}; 
  
template <> 
class Test <int> 
{ 
public: 
   Test() 
   { 
       // Initialization of data members 
       cout << "Specialized template \n"; 
   } 
}; 
  
int main() 
{ 
    Test<int> a; 
    Test<char> b; 
    Test<float> c; 
    return 0; 
} 
Output
Specialized template  
General template 
General template 

How does template specialisation work?

When we write any template-based function or class, the compiler creates a copy of that function/class whenever the compiler sees that being used for a new data type or a new set of data types(in case of multiple template arguments).
If a specialised version is present, the compiler first checks with the specialised version and then the main template. The compiler first checks with the most specialised version by matching the passed parameter with the data type(s) specified in a specialised version.

Template Parameter

Template parameters can be types, non-types, and templates.

  1. Types: Types are the most often used template parameters.
  2. Non-Types:
  • lvalue reference
  • nullptr
  • pointer
  • enumerator
  • integral

Integrals are the most used non-types. std::array is the typical example because you have to specify at compile time the size of a std::array:

Std::array<int, 3>  myarray{1, 2, 3};

Can we pass non-type parameters to templates?

The non-type parameters can be passed to templates. They mainly focus on passing the constant expression i.e address of a function, object or static class member at compile time. Non-type parameters are also used for specifying max or min values for a particular instance of a template.

Source Code

template <std::string * temp> //pointer to object
void f()
{
   cout << *temp << endl;
}

template <std::string & temp> //reference to object
void g()
{
     cout << temp << endl;
     temp += "...appended some string";
}

std::string s; //must not be local as it must have external linkage!

int main() {
        s = "can assign values locally";
        f<&s>();
        g<s>();
        cout << s << endl;
        return 0;
}

Output:

Output
Can assign values locally
Assign values locally
We can assign values locally...appended some string

Create Multi-File Templates

Item templates may only specify one item, but sometimes the item is made up of multiple files.

  • A file that contains code for the form
  • The file that contains designer information for the form
  • A file that contains embedded resources for the form

The set of parameters spans all files of a multi-file template. If you use the same parameter $PARAM$ in several files of a multi-file template, it will have the same value in all related files when the template is applied.

If a multi-file template has editable parameters, the Hot Spot Session, which deploys when you apply this template, will guide you through all created files where the user input is required.

Manually create a multi-file item template.

  • Create an item template as you would manually create a single-file item template, but include each of the files that constitute the multi-file item.
  • In the ‘.vstemplate’ XML file, add a ‘ProjectItem’ element for each individual file, and add a ‘TargetFileName’ attribute to this element. Set value of the TargetFileName attribute to ‘$fileinputname$.FileExtension’, where FileExtension is the file extension of the file that is included in the template. 

 Multi-file item template example:

<ProjectItem TargetFileName="$fileinputname$.vb">
    Form1.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.Designer.vb">
    Form1.Designer.vb
</ProjectItem>
<ProjectItem TargetFileName="$fileinputname$.resx">
    Form1.resx
</ProjectItem>
  • Select the files that need to be included in your template, right-click the selection, and choose Send to > Compressed (zipped) folder.

The files that you have selected are compressed into a .zip file.

  • Copy the .zip file to the user-item template location. The directory is ‘%USERPROFILE%\Documents\Visual Studio 

<Version>\Templates\ItemTemplates’ by default.

  • Close Visual Studio and then open it.
  • Create a new project, or open an already existing project, and then select Project > Add New Item or press Ctrl+Shift+A.

The multi-file item template appears in the ‘Add New Item’ dialogue box.

Example

<VSTemplate Version="2.0.0" Type="Item"
    xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
    <TemplateData>
        <Name>Multi-file Item Template</Name>
        <Icon>Icon.ico</Icon>
        <Description>An example of a multi-file item template</Description>
        <ProjectType>VisualBasic</ProjectType>
    </TemplateData>
    <TemplateContent>
        <ProjectItem TargetFileName="$fileinputname$.vb" SubType="Form">
            Form1.vb
        </ProjectItem>
        <ProjectItem TargetFileName="$fileinputname$.Designer.vb">
            Form1.Designer.vb
        </ProjectItem>
        <ProjectItem TargetFileName="$fileinputname$.resx">
            Form1.resx
        </ProjectItem>
    </TemplateContent>
</VSTemplate>

Standard Template Library in C++

A standard template library in C++ is a repository of C++ template classes. These template classes help in implementing commonly used algorithms and data structures. These template classes can be used with any user-defined type as well as a built-in type. STL algorithms are container-independent and thus reduce the complexity of the library. This approach implements compile-time polymorphism over run-time polymorphism.

This brings us to the end of the blog on Templates in C++. Hope this helps you to up-skill your C++ skills. To learn more about programming and other related concepts, check out the courses on Great Learning Academy

Also, if you are preparing for Interviews, check out these Interview Questions for C++ to ace it like a pro.

Template in C++ FAQs

What are CPP templates?

In C++, a template is referred to be a design pattern or recipe for developing a generic class or function. Simply put, you may use templates to construct a single function or single class that works with several data types. A very useful element of C++ is the generic functions or classes, sometimes referred to as C++ templates. The data type variable is defined by an angled bracket in a parameter (t) and the keyword “template” in the C++ programming language.

What types of templates are there in CPP?

Function templates, class templates, and, as of C++14, variable templates are the three categories of templates. Templates are always non-variadic in older versions of C++. However, the templates in C++ can either be variadic or non-variadic. 

How many templates are there in CPP?

As of the latest version, CPP14, there are three main templates, namely function, class , and variable templates.

Why do we use templates in CPP?

When creating generic constructs like queues, lists, stacks, and vectors that can be used with any type, templates come in quite handy. In contrast to inheritance and composition, which enable the reuse of object code, C++ templates enable the reuse of source code.

What are the different types of templates?

Different types of templates supported by C++14 are, class templates, function templates, vardiac, and non-vardiac templates. 

What is the use of templates?

In general, an instrument for imposing a consistent layout, appearance, and feel across several pages or inside content sections is a template. Any pages or regions that are based on a template are immediately modified whenever a template is altered. This concept is applied in codes as well, so that we can use a defined layout multiple times. 

What are two types of templates?

The two major categories of templates are – class templates and function templates.

What is a template example?

A class or a function whose layout can be used as many times as required in a code is made into a template. For example, we can create templates for functions like sort(), minimum(), maximum(), arrayPrint(), Fibonacci(), etc. Similarly, we can create class templates for heavy structures, for instance, linkedList(), Queue(), Stack(), Book(), etc. 

What is a template and what are its advantages?

With the aid of C++ templates, you can create a group of classes or functions that can handle various forms of data. When there is a need to duplicate the same code across many types, we use templates. Several advantages of templates are as follows:
They increase the efficiency of the program by reducing the developing-time when used in combination with STL
They permit type generalization.
They reduce the quantity of repetitive code you must type.
They assist in writing type-safe code.
They are assessed during compilation.
They aid in creating extremely powerful libraries

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top