Insight 23.1.1.
Templates are not compiled directly. They are a blueprint for generating code. When you use templated code, the compiler uses that blueprint to create the specific versions needed for the types you use.
int myMax(int a, int b) {
return (a > b) ? a : b;
}
double myMax(double a, double b) {
return (a > b) ? a : b;
}
template <typename T>
T myMax(T a, T b) {
return (a > b) ? a : b;
}
T
, which will be replaced with the actual data type when the function is called. You can think of <typename T>
as saying โthis template works with any one data type that we will refer to as Tโ.
T
as the type for the parameters and the return value. This says โwhatever type T
is, use that as the return type and parameter typesโ.
myMax(3, 5)
, the compiler creates a version of myMax
where T
is int
. If we call myMax(3.5, 2.1)
, it creates a version where T
is double
.
myMax
will be used to generate three different concrete versions of the code, one each for int
, double
, and char
:
T
is supposed to be, it will result in a compilation error. For example, if we try to call myMax
with an int
and a double
, the compiler wonโt know if it should use int
or double
for T
:
<TYPENAME>
after the function name. When we do this, the compiler knows exactly which type to use for T
. It will try to convert any other types will be converted to the specified type: