ConcepttheGenericsinC++
theGenericsIt is a method of writing code that makes you able to build one code that fits more than one type of data, and when you need to use this code, you can use it as it is or specify the type of data you want to work with according to your need.
For every class, interface or function you find the code < >
is within its definition, know right away that it is designed to handle more than one data type.
benefittheGenerics in C++
You do not have to use a methodtheGenerics,But learning it will help you a lot in developing your code, and making its size smaller and easier in the case of modification.
For example, you can build a function that you can pass an array of any type and print the values of the elements in it.
technical terms
Generic Function: Defines a function that deals with more than one data type.
Generic Class: means a class definition that deals with more than one data type.
Bounded Type Parameters: means defining a class or function that deals with a specific type in addition to all types derived from it, that is, those that inherit from it.
Characters used intheGenericsinC++
In the following table, we mentioned the common characters among programmers when dealing withtheGenerics.
Common Characters in Generics | |
---|---|
T |
acronymType,It means any kind. We usually use it when building code that handles any data type. |
N |
acronymNumber,It is intended to be any type that is used to store numbers. We usually use it when building code that deals with numbers of any kind, like( int - float - double etc..). |
E |
acronymElement,Refers to an element that does not have a specific type. We usually use it when building code that deals with array elements of any type. |
K |
acronymKey,Refers to a key that does not have a specific type. We usually use it when building code that deals with the keys of an object that stores data in a formkey / value. |
V |
acronymValue,It means a value that has no specific type. We usually use it when building code that deals with the values of an object that stores data in a formkey / value. |
Note: All the characters mentioned in the table have no effect on the code, and you can put any letter or word in their place, but we advise you to adopt them.
How to define an undefined type inC++
Any character that you will use in a function or class to indicate that its type is not specified, must be defined immediately before defining the function or class because it is considered specific to what you define after it only.
The general form of defining an unspecified type is as follows, noting that you can put any letter or name you want instead of the letterT
.
template <typename T>
In case you want to define more than one undefined type, you must put a comma between them as follows.
template <typename T1, typename T2>
In the following example, we have defined a function that prints the value of any variable we pass to it, whatever its type.
Then we called it three times, passing it a different value each time.
#include <iostream> using namespace std; // which is specific to the function that we will define after E. Here we have defined an undefined data type that we named template <typename E> // then it prints it x when called, we pass it a value of any type where the printVar parameter is. Here we have defined a function named void printVar(E x) { cout << x << endl; } // main() Here we have defined the function int main() { // string and a variable of its type float is a variable of its type , here we have declared a variable of its type int x = 10; float y = 7.5; string name = "Mahamad"; // three times passing a value of a different type each time printVar() Here we called the function printVar(x); printVar(y); printVar(name); return 0; }
• We will get the following result when running.
10 75 @mhamad
The type that you define before anything you can make it adjacent to when defining it, but we didn't do that until we can write a clear explanation for you.
So the function printVar()
could have been defined like this and it is better to define it like this as well.
template <typename E> void printVar(E x) { cout << x << endl; }
When calling the function, printVar()
you can specify the data type - which you want to put yourself in the place of any undefined type - instead of having the compiler do that, and this will make your program faster to execute.
So it would be a good idea to specify the type of value that we will pass to the function printVar()
when it is called as follows.
printVar<int>(x); // int directly with type printVar() in function E here the compiler will swap the character printVar<float>(y); // float directly with type printVar() in function E here the compiler will roll the character printVar<string>(name); // string directly with type printVar() in function E here the compiler will alter the character
Comprehensive examples of dealing withtheGenericsinC++
How do you build a function that you can pass a parameter that has no type specified in C++
The following example is an application of an ideaGeneric FunctionFrom it, you will learn how to build a function that you can pass to a parameter that does not have a specific type.
In the following example we have defined the character E
as an undefined data type.
Then we defined a function whose name printArray()
when called, we pass it an array of any type with the number of its elements passed, and it prints all the values in it.
Practical example of an idea Generic Function in C++
#include <iostream> using namespace std; // which is specific to the function that we will define after E. Here we have defined an undefined data type that we named template <typename E> // length and the size of the array where the parameter arr is called when we call it we pass an array of any type where the parameter printArray is here we have defined a function named void printArray(E arr[], int length) { // on one line arr Here we have created a loop that displays all the elements of the array for(int i=0; i<length; i++) { cout << arr[i] << " "; } // After displaying all the elements, it will be moved to a new line cout << endl; } // main() Here we have defined the function int main() { // Here we have defined three arrays, each of them containing a different type of data int arr1[] = {1, 2, 3, 4, 5}; char arr2[] = {'a', 'b', 'c', 'd', 'e'}; string arr3[] = {"I'm", "learning" ,"C++", "in", "harmash.com"}; // specifying the type of each array to be passed arr3, arr2 and arr1 to print the values of the three arrays printArray() here we called the function printArray<int>(arr1, 5); printArray<char>(arr2, 5); printArray<string>(arr3, 5); return 0; }
• We will get the following result when running.
1 2 3 4 5 abcde I'm learning C++ in harmash.com
So here every time you call the function printArray()
the character is automatically swapped E
with the type of array passed to it.
How to build a function that returns a value that has no type defined in C++
The following example is an application of an ideaGeneric FunctionAlso, but you will learn from him how to build a function that returns a value that does not have a specific type.
In the following example we have defined the character T
as an undefined data type.
Then we defined a function whose name divide()
when called, we pass two numbers to it, and it returns the result of dividing the two numbers by the type we want.
The idea here is that we want to make the function accept integers and decimal numbers (in which there are commas) with the ability to get the result including any numbers with or without commas.
Example how to build a function that returns a value that has no type specified in C++
#include <iostream> using namespace std; // and is specific to the function that we will define after T here we have defined an undefined data type we named template <typename T> // it returns the result of its division with the type we want y and x when called we pass it two numbers in place of the two parameters divide Here we have defined a function named T divide(double x, double y) { return x/y; } // main() Here we have defined the function int main() { // int in the original function will be replaced by type T to find the result of dividing 5 by 2, specifying that the divide() character here we called the function cout << "divide<int>(5,2) = " << divide<int>(5,2) << endl; // double in the original function will be replaced by type T to find the result of dividing 5 by 2, specifying that the character divide() here we called the function cout << "divide<double>(5,2) = " << divide<double>(5,2); return 0; }
• We will get the following result when running.
divide<int>(5,2) = 2 divide<double>(5,2) = 2.5
How to build a class that deals with different types in C++
The following example is an application of an ideaGeneric ClassFrom it, you will learn how to build a class that deals with different types.
In the following example, we have defined a class whose name Box
has an unknown data type and we denoted it with the letterT
.
In this class, we define a variable whose name is x
its typeT
.
Then we have defined a function whose name getX()
is used to fetch the value of the variablex
,And its name is a function setX()
used to determine the value of a variablex
.
Finally, we experimented with creating two class objects Box
as follows:
The first object in which we specify that a value
x
will be of typeint
.The second object in which we set a value to
x
be of typestring
.Example How to build a class that deals with different types in C++
#include <iostream> using namespace std; // It is specific to the class that we will define after T. Here we have defined an undefined data type that we named // A subject in the T class that will be replaced by each Box character when creating an object from the T class of the type we specify for the character template <typename T> class Box { private: T x; public: void set(T x) { this->x = x; } T get() { return x; } }; // main() Here we have defined the function int main() { // int in the original class it will be replaced by type T with specifying that the character intBox is named Box here we have defined an object of the class Box<int> intBox; // also int which has its type x this value will be stored in the variable .int here we have entered a value of its type intBox.set(100); // also int the value to be returned here is of type .x here we have returned the value that is stored in the variable cout << "intBox contains: " << intBox.get() << endl; // string in the original class will be replaced by type T specifying that the stringBox is called Box Here we have defined an object of the class Box<string> stringBox; // Also, string whose type is x will be stored in the variable .string. Here we have entered a value of its type stringBox.set("I can store string value"); // also string the value returned here is of type .x here we returned the value that was stored in the variable cout << "stringBox contains: " << stringBox.get(); return 0; }
• We will get the following result when running.
intBox contains: 100 stringBox contains: I can store string value
Technical information
We defineGeneric ClassWhen we have operations in this class that can be applied to more than one type.
Then, instead of creating a class to deal with each type separately, we define a general classGeneric ClassWe specify the type we want to deal with while creating an object of this class.
Attention
When creating an object fromGeneric ClassYou will be forced to specify all types of unspecified data in it or you will see an errorMissing template arguments .