My Blog
Articles related to programming, computer science, technology and research.

01/12/2016 Categories: C++ Programming. No Comments on Generic Programming in CPP



To generate short, simple code and to avoid duplication of code, C++ provides templates to define the same piece of code for multiple data types. With templates, programmers can define a family of functions or classes that can perform operations on different types of data.


Templates comes under the category of meta-programming and auto code generation, where the generated code is not visible in general. Through templates, C++ supports generic programming.


Generic programming is a type of programming where the programmer specifies a general code first. That code is instantiated based on the type of parameters that are passed later in the program or at execution.


Entities such as a class or function created using generic programming are called generics.


Use of Templates


Following are the uses of templates in programming:

  • Templates are widely used to implement the Standard Template Library (STL).
  • Templates are used to create Abstract Data Types (ADTs) and classify algorithms and data structures.
  • Class templates are generally used to implement containers.



Function Templates


A function template is a function which contains generic code to operate on different types of data. This enables a programmer to write functions without having to specify the exact type of parameters. Syntax for defining a template function is as follows:



As shown above, the syntax starts with the keyword template followed by a list of template type arguments or also called generic arguments.


The template keyword tells the compiler that what follows is a template. Here, class is a keyword and Type is the name of generic argument.


Following program demonstrates a template function or function template:



In the above program compiler generates two copies of the above function template. One for int type arguments and the other for float type arguments. The function template can be invoked implicitly by writing summ(val1, val2) or explicitly by writing summ<int>(val1, val2).


Templates vs. Macros


As templates and macros perform similar tasks, we need know what is the difference between them. Following are the differences between templates and macros:




Guidelines for Using Template Functions


While using template functions, programmer must take care of the following:


Generic Data Types


Every template data type (or generic data type) should be used as types in the function template definition as type of parameters. If not used, it will result in an error. Consider the following example which leads to an error:



Also using some of the template data types is also wrong. Consider the following example which leads to an error:



Overloading Function Templates


As normal functions can be overloaded, template functions can also be overloaded. They will have the same name but different number of or type of parameters. Consider the following example which demonstrates template function overloading:



Whenever a compiler encounters the call to a overloaded function, first it checks if there is any normal function which matches and invokes it. Otherwise, it checks if there is any template function which matches and invokes it. If no function matches, error will be generated.


From the above example you can see that for the call summ(a, b), normal function is invoked and for the call summ(p, q), template function is invoked.


Recursive Template Functions


Like normal functions, template functions can also be called recursively. Consider the following example which demonstrates a recursive template function that calculates the factorial of a number:



Function Templates with User-defined Types


We can also pass user-defined types like class, structure, union as arguments to a function template. Consider the following function template which demonstrates passing a class as an argument:



Class Template


Using templates programmers can create abstract classes that define the behavior of the class without actually knowing what data type will be handled by the class operations. Such classes are known as class templates. Syntax for creating a class template is as follows:



Syntax for creating an object of the template class is as follows:



The process of creating an object of a template class or creating a specific class from a class template is called instantiation. The instantiated object of a template class is known as specialization. If a class template is specialized by some but not all parameters it is called partial specialization and if all the parameters are specialized, it is a full specialization.


Following program demonstrates creating a class template and using it:



The template data types allows default arguments. Syntax for specifying default data types is as follows:



We can define member functions of a class template outside the class. Syntax for doing it is as follows:



Class Template and Friend Functions


A friend function is a normal (non-member) function which can access the private members of a class. A function can be declared as a friend function inside the template class using the following syntax:



Following example demonstrates a friend function in class template:



Class Templates and Static Variables


We know that static variables are shared by all the objects of a class. In class templates, all the objects of same type share the same static variable. Following program demonstrates a static variable inside a class template:



Class Templates and Inheritance


A template class can be used in inheritance in the following ways:

  • Deriving a class template from base class.
  • Deriving a class template from a base class which also a class template and adding more template members to it.
  • Deriving a class template from a base class which is a template class but disallowing the derived class and its derivatives to have template features.
  • Deriving a non-template base class and adding some template members to it.


The syntax for declaring a derived class from base class which is a template class is as follows:



The derived class can be either a template class or a non-template class. If the derived class is a template class, then type of template arguments must be specified while creating its object. If the derived class is a non-template class, then type of template arguments must be specified during derivation itself as follows:



Following example demonstrates creating a derived class which is a template class from a base class which also a template class:



Advantages and Disadvantages of Templates


The advantages of templates are as follows:

  • Templates not only increases reusability of code but also makes the code short and simple.
  • A single template can handle different types of parameters.
  • Testing and debugging becomes simple.
  • Templates support on-demand compilation i.e., only necessary template instances are compiled. In a program without templates all classes are compiled irrespective of the needed ones.


The disadvantages of templates are as follows:

  • Some compilers doesn’t support all template features. This reduces portability.
  • Time needed to debug the code and resolve a error by the compiler needs more time.
  • As templates are declared in the header, code is visible to all programs. This is in contradiction to information hiding.


Bubble Sort using Function Template


Following program performs Bubble sort using function templates:



Linked List using Class Template


Following program demonstrates a linked list using class template:


Input and output for the above program are as follows:



Related Links:

Popular Posts:

Leave a Reply

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

Scroll Up