templates in C++

Templates are an interesting feature of C++. It is used for generic Programming. Generic Programming is an approach of programming where generic types are used as parameters in algorithms to work for a variety of data types.

Table of Contents 

  1. What is Template in C++?
  2. Types of Templates in C++
  3. Function Template in C++
  4. Class Template in C++
  5. Advantages of Using Templates in C++
  6. Disadvantages of Using Templates in C++
  7. Overloading of Template Function
  8. Templates Specialization 
  9. Function Specialization
  10. Class Specialization
  11. Template Parameter
  12. Standard Template Library in C++

 What is Template in C++?

Templates are a very powerful feature of C++. It is used for generic Programming. It is also known as generic functions or classes. A template is a blueprint or formula for creating a generic class or a function. In a simple way, you can create a single function or single class to work with different data types using templates. A keyword template is used for the template’s syntax and angled bracket in a parameter (t), which defines the data type variable. 

Types of Templates in C++

There are two types of templates in C++

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

Function Template in C++

Function template is working as a normal function. A single function template works with multiple data types simultaneously, but a standard function works only with one set of data types.

Syntax of Function Template

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

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

A simple example of a function template:

Source Code:

Output:

Class Template in C++

Class templates are like function templates. They are known as generic templates. They define a family of classes in C++. 

Syntax of Class Template

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

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

Source Code:

Output:

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 makes 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 Template Function in C++

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

Templates Specialization 

In C++, a template is a feature. A template is 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++.

Function Specialization

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

 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

 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 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};

Source Code

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

template <std::string &amp; 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<&amp;s>();
        g<s>();
        cout << s << endl;
        return 0;
}

Output:

can assign values locally

can assign values locally

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. 

 For 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’ dialog 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 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.

0

LEAVE A REPLY

Please enter your comment!
Please enter your name here

14 + three =