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
- Program to find the number of men initially
- Remove elements to make array satisfy arr[ i+1] < arr[i] for each valid i
- Find the node whose sum with X has minimum set bits
- Salt and Pepper Noise removal using C++
- Dynamic Constructor in C++ with Examples
- C++ Stream Classes Structure
- OpenMP | Hello World program
- Odd Even Transposition Sort / Brick Sort using pthreads
- Chat application between two processes using signals and shared memory
- Number of positions such that adding K to the element is greater than sum of all other elements
- Maximum length of subarray such that sum of the subarray is even
- Intel Graphics Software Engineer Interview Experience
- OpenMP | Introduction with Installation Guide
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.