Topic :Templates in C++ Programming Language: Class Templates: | Function Templates:

Templates:

It is a dominant feature of C++ that allow us to use templates. Templates provide us the basis of generic programming. The templates are the formula or blueprints for making a generic function or class. In this way of programming, your functions and classes will be more generalized rather than the specialized. In other words, it makes it easier for you to use different data types in your program by creating one class or a function. Also, your primary focus will be towards the logic and quality of programming. The more you will concentrate on your algorithmic thoughts, the better your programming will. We can also refer the C++ Templates as generic classes. Often in large projects, we feel the need of templates to enhance the flexibility and re-usability of our programs.



Arrays: Infobrother:

Let's suppose we write a simple Program "Calculator". This program can add, subtract, or can perform any Math Operation on Integers. the Program is good, working fine, but how about if we want to perform some math operations on a float. do we need to create another program? Obviously, we have to, because Our program just works On integers. so for any other data type, we have to write another program if C++ didn't provide Its dominant Feature like "Template". so template makes our life easier in this case.





Class Templates:

It’s easy to create a class template for the purpose to make a generic class. The Class template is a standard class that is used to combine different data types. If you are not using the templates, it will be breath-taking for you to manage different classes for the variety of data types. On the other hand, class templates help you to reuse the same code for many data types.



Declaration of Class Template:
Template <class T> class className 
{
    public:
        T number;
        T Method();
};

  • In Above Syntax:

    » Template is the keyword to declare template Class.
    » class is the keyword to declare class template.
    » T is the placeholder name for a data type used by the function.
    » className is the name for the template class.



Defining Object of Template class:

As it is a general class for all data type, you have to declare the data type of every object to make it reusable. The basic syntax to make the object of Template Class is -


Class-name <Data-type> class-object;

  • In Above Syntax:

    » Class-name is the name for Template Class. it could be any name just like variable name.
    » Data-type could be any valid data type that we want to use for template class.
    » Class-object is the object for the template class.



Look at the Given example to know, how exactly we can create the object of Template class for different data type.


class-name <int>    classObject; 
class-name <string> classObject;
class-name <float>  classObject;

Now here let's have an short and simple example to clear the concept of Class Template: We will create an simple Calculator Program using class template:



/* Example: Template Class: InfoBrother:*/
 
#include <iostream>
using namespace std;
 
template <class T> //Template class:
class Calculator
{
    private:
        T var1, var2; //variable of type "T"
 
    public:
 
    Calculator(T num1, T num2) //method having argument of type "T":
    {
        var1 = num1;
        var2 = num2;
    }
 
    void showResult() //method to display result on screen: 
    {
        cout << "\n Addition: "<<var1<<" + "<<var2<< " = " << add() << endl;
        cout << " Subtraction: "<<var1<<" - "<<var2<< " = " << sub() << endl;
        cout << " Multiplication: " <<var1<<" x "<<var2<< " = " << multi() << endl;
        cout << " Division: " <<var1<<" / "<<var2<< " = " << divid() << endl;
        cout<<"==========================================="<<endl;
    }
 
    // Methods of type T: will return the result:
    T add() { return var1 + var2; } 
 
    T sub() { return var1 - var2; }
 
    T multi() { return var1 * var2; }
 
    T divid() { return var1 / var2; }
};
 
int main()
{
    Calculator<int> intCalc(2, 1);
    Calculator<float> floatCalc (2.4, 1.2);
 
    cout << "TEMPLATE CLASS FOR INTEGERS:" << endl;
    intCalc.showResult ();
 
    cout << endl << "TEMPLATE CLASS FOR FLOAT:" << endl;
    floatCalc.showResult ();
 
    return 0;
}


We have declared a class template named Calculator. And, the class has two private member variables of type T. These members are var1 and var2, and we created a constructor to initialize these. Our program has more than one-member functions to sort out the addition, subtraction, multiplication and division of the given numbers. These mathematical results are the values of the user-defined data type such as int and float. We have defined the function showResult() to show the last result on computer screen. As far as the main() function is concerned, we have defined the two calculator objects intCalc and floatCalc. These both objects belong to different data types, i.e., int and float. We used constructors to represent the different values. The point to remember is that we gave the data types while creating the objects of the class. These data types, in fact, covered the class definition to use these objects.



In a template class, the code that identifies the parameterized data type appears just once before the class definition; it is a mistake to repeat it before each function implementation.


Function Templates:

A function template behaves same like the normal functions. But, as it is function template there could be a difference. In fact, a function template allows us to use many data types in one function. The concept is same as the class template. As in the class model, we can give a variety of data types in one class. Same is the case here. In function template, we can offer a variety of data types in one function. We can also use the function overloading and overriding concepts to implement the different data types with the needed function declaration. However, it’s the better approach to use function templates to reuse the code. So, in this way our programming efforts and maintenance of code will be minimized.


Declaration of Function Templates:

Same like a class template, it also begins with the keyword template. Let’s see the syntax for declaring a function template.



Template <class T> 
T function_Name(T argumen_list)
{
     //body of function: 
}


  • In Above Syntax:

    » Template is the keyword to declare template function.
    » class is the keyword same like class template. but Here is an ease, we can also use another keyword typename instead of the class. so when we pass an argument of a data type to function_name(), compiler will generates a new version of function_name() for the given data type.
    » T is the placeholder name for a data type used by the function.



Let's have an example here to understand, how we can create template function in C++ programming, and how Template function work exactly:


/* Example: Function Template: InfoBrother:*/
 
#include <iostream>
using namespace std;
 
template <class T> 
//swap function: arguments pass by reference:
void Swap(T &var1, T &var2) 
{
    T temp; //temporary variable of type "T".
    temp = var1;
    var1 = var2;
    var2 = temp;
}
 
main()
{
    int int1 = 5, int2 = 10;
    float float1 = 5.1, float2 = 10.5;
    char char1 = 'a', char2 = 'b';
 
    cout << "Before passing data to function template.\n";
    cout << "int1 = " << int1 << "\nint2 = " << int2;
    cout << "\nfloat1 = " << float1 << "\nfloat2 = " << float2;
    cout << "\nchar1 = " << char1 << "\nchar2 = " << char2;
 
    Swap(int1, int2);
    Swap(float1, float2);
    Swap(char1, char2);
 
    cout<<"\n============================================"<<endl;
    cout << "After passing data to function template.\n";
    cout << "int1 = " << int1 << "\nint2 = " << int2;
    cout << "\nfloat1 = " << float1 << "\nfloat2 = " << float2;
    cout << "\nchar1 = " << char1 << "\nchar2 = " << char2;
 
    return 0;
}


In the above example: We call the function by passing a reference to swap the variable.



A template is anything that serves as a pattern. For example, some word processing programs come with built-in templates for resumes and business letters that you can use as a basis for your own documents.







I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement