void insert (int a, int b[], int index) {
b[index] =a;
}
void insert (char a, char b, int index) {
*(b+index) = a;
}
The goal is to make these two functions generalized generic functions, but I don't understand the concept of generic because it's my first time.
If you generalize those two functions, I'm going to compare them and study them ㅠ<
c++ generic function
When writing a logic, generalization programming is not limited to a particular type, but rather writing code that can operate in a variety of types.
In C++, generalization programming is possible through a template, and several classes and functions are provided by the standard in the form of the Standard Template Library (STL).
There are several types of insert()
as shown below.
void insert(int a, int b[], int index) { b[index] = a; }
void insert(char a, char b[], int index) { b[index] = a; }
void insert(double a, double b[], int index) { b[index] = a; }
void insert(std::string a, std::string b[], int index) { b[index] = a; }
Put the a
value into a specific index
of b
.
The above functions will be written in the same way as b[index] = a;
, but since the types are different, all of them must be overloaded according to the array type.
The contents of the function are all the same as b[index] = a;
, but they are all different types, so you have to fill them out one by one.
This is not good because the code is redundant, very cumbersome, and causes mistakes.
In C++, you can create a template and keep the content intact, but you can act by replacing certain types.
template<typename T>
void insert(T a, T b[], int index) {
b[index] = a;
}
int a1[10] = {};
insert(1, a1, 0);
double a2[10] = {};
insert(1.0, a2, 0);
The insert
function template above has the contents of b[index] = a;
but determines T
that is to be replaced at the time of the call.
insert(1, a1, 0);
becomes T=int
because insert(1, a1, 0);
is an integer array, and insert(1.0, a2, 0);
becomes
a2
because is a real array.
Unlike the first code, you can create code for multiple types by creating only one template.
© 2024 OneMinuteCode. All rights reserved.