Templates are like a way to simplify making overloaded functions, by allowing for a function with generic data types to be written, to have the compiler change at compile time.
The Generic Version of this would look like:
template<typename T>
T functionName(T value1, T value2, ...)
{
// do stuff...
return T;
}
Think of something like where you want to determine the max value of two variables. Well, you would have to have a series of overloaded functions,for chars, strings, ints, etc. This way, you only need to write it once, assuming you don’t have multiple numbers of parameters between types.
template<typename T>
T maxValue(T v1, T v2)
{
if (v1 > v2)
{
return v1;
}
else {
return v2;
}
}
Notice that “T” becomes replaced with the appropriate data type.
In this case we have the same data type used between both parameters. You can define multiple types, but you have to give it a template type of T1, T2, etc to make it work so the compiler can figure it out. More on that later.
Note: If you tried this with your class, Circle for example, it wouldn’t work since the class doesn’t know how to compute greater than yet.
The Basics of Templates in C++ was originally found on Access 2 Learn