Template basics
One definition of the word “template” is “a gauge, pattern, or mold (such as a thin plate or board) used as a guide to the form of a piece being made. “ This definition can be applied to templates in C++.
In C++, templates serve as patterns or molds for functions and classes, allowing the creation of actual functions and classes. From this perspective, templates are not real functions or types themselves; rather, they act as guides for generating concrete functions and types. To better understand this definition, let us take a look at the following code sample:
#include <cstdio>
template<typename T>
T add(T a, T b) {
return a + b;
}
int main() {
int result_int = add(1, 4);
float result_float = add(1.11f, 1.91f);
printf("result_int = %d\r\n", result_int);
printf("result_float = %.2f\r\n", result_float);
return 0;
}
In this example, we have a template function, add, with the...