Generic programming, English called Generic programming
Can be understood as, universal meaning, universality, programming.
For example, you would implement a function to compare the size of two numeric values, which could be either int or string. For the first attempt, we intuitively think of defining multiple overloaded functions. As follows:
int compare (const string &V1, const string &v2)
{
if (V1 < v2) return-1;
if (V2 < v1) return 1;
return 0;
}
int compare (const int &V1, const int &V2)
{
if (V1 < v2) return-1;
if (V2 < v1) return 1;
return 0;
}
These two functions are almost identical except for the type of the parameter. As the types of comparisons increase, we have to define a number of similar and redundant functions.
Generic programming is designed to solve such problems, so that we can write code independently of any particular type.
Templates are the basis for C + + generic programming. The template definition starts with the keyword template followed by a list of templates parameters. The template parameter list is surrounded by <> with one or more template parameters separated by commas.
For example, the above requirements can be written as follows:
Template <typename t>
int compare (const t &V1, const T &V2)
{
if (V1 < v2) return-1;
if (V2 < v1) return 1;
return 0;
}
C + + generic programming and template learning