👉🏻 If you want to enjoy the full experience exploring this pdf, check it out here Templates
int add (int x, int y){
return x + y;
}
double add (double x, double y){
return x + y;
}
/*so here I wrote the function 2 times to be
able to add integers and doubles
what if I want to pass a string, it is not logical
to type a definition for every data type
here is when we use templates*/
//<typename T> is called template prefix
//T x is generic data type
//T add() is type parameter
template <typename T>
T add (T x, T y){
return x + y;
}
/*first step to convert the function to a function template
is writing the template keyword followed by <>
inside the <> we type a special parameter
we either call it class or typename (typename is more preferred)
then we give this parameter a name and it is 'T' by convention
then we replace every data type in the function definition with 'T' */
//If you want to pass parameter of different types,
//you have to explicitly tell the compiler how to treat them
//or which type to choose
add(1, 1.1); //would result in an error
<int> add(1, 1.1); //tells the compiler to treat both as int
//the error goes away
What if I have a variable number of parameters?
template<typename T>
T add(T start){
return start;
}
template<typename T, typename... Args>
T sum(T start, Args...args){
return start + sum(args...);
}
sum(1, 2, 3);
/* here is how it works
sum(1, (2,3)){
return 1 + sum(2,3);
}
sum(2,3){
return 2 + sum(3);
}
sum(3){
return 3 + 0;
}
so, it returns 3 + 2 + 1 = 6