templates allow you to create functions and classes independant of the types that are applied to them....
You can take a common idea (maybe a container or smart pointer) and provide the code nessasary without having to concentrate too much if this code will be used with say an int or a char or a user defined class. The compiler uses the template to create the actual code needed (say a version for int, a version for char...etc)
So you can do this with 1 temaplate;
Code:
#include <iostream>
#include <string>
template <class T>//template function
void Print(const T& t){
std::cout << t << std::endl;
}
int main(){
std::string str("Hello World");
int x = 20;
double d = 569.789;
//compiler produces code to make a Print for string,int and double
Print(str);
Print(x);
Print(d);
}
And the compiler will turn this to;
Code:
#include <iostream>
#include <string>
void Print(std::string& t){
std::cout << t << std::endl;
}
void Print(double& t){
std::cout << t << std::endl;
}
void Print(int& t){
std::cout << t << std::endl;
}
int main(){
std::string str("Hello World");
int x = 20;
double d = 569.789;
Print(str);
Print(x);
Print(d);
}
The benefit to you is that you need only define your code once...not for every possible value that can be applied to it