Generics is the idea to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes and interfaces. For example, classes like an array, map, etc, which can be used using generics very efficiently. We can use them for any type.
The method of Generic Programming is implemented to increase the efficiency of the code. Generic Programming enables the programmer to write a general algorithm which will work with all data types. It eliminates the need to create different algorithms if the data type is an integer, string or a character.
The advantages of Generic Programming are
- Code Reusability
- Avoid Function Overloading
- Once written it can be used for multiple times and cases.
Generics can be implemented in C++ using Templates. Template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter.
Generic Functions using Template:
We write a generic function that can be used for different data types. Examples of function templates are sort(), max(), min(), printArray()
7 7 g
Generic Class using Template:
Like function templates, class templates are useful when a class defines something that is independent of data type. Can be useful for classes like LinkedList, binary tree, Stack, Queue, Array, etc.
Following is a simple example of template Array class.
1 2 3 4 5
Working with multi-type Generics:
We can pass more than one data types as arguments to templates. The following example demonstrates the same.
Constructor Called Constructor Called
- Templates in C++ vs Generics in Java
- Wheel Factorization Algorithm
- Stack of Pair in C++ STL with Examples
- Modulo Operator (%) in C/C++ with Examples
- fpclassify() method in C/C++ with Examples
- Operator Overloading '<<' and '>>' operator in a linked list class
- Set of Vectors in C++ STL with Examples
- Priority Queue of Vectors in C++ STL with Examples
- How to find the Entry with largest Value in a C++ Map
- Visibility Modes in C++ with Examples
- Two way communication between Client and Server using Win32 Threads
- Program to implement Separate Chaining in C++ STL without the use of pointers
- Speed up Code executions with help of Pragma in C/C++
- Vector of Vectors in C++ STL with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.