can anybody tell me what is the usage of templates in a cpp file
when do we use it and why??if its possible can u give me a simple example about .t
Printable View
can anybody tell me what is the usage of templates in a cpp file
when do we use it and why??if its possible can u give me a simple example about .t
Templates are used when you dont know the exact type of variable you want to use. Say you dont know if its going to be int or char. You use a template function which is good for all variable types.
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;
And the compiler will turn this to;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);
}
The benefit to you is that you need only define your code once...not for every possible value that can be applied to itCode:#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);
}
Datastructures, e.i stack and queue.Quote:
when do we use it and why??if its possible can u give me a simple example about .t
>when do we use it and why??
You use templates when the type of the data will change yet not effect the behavior. An example is a vector, you can have a vector of almost any type yet the behavior of the vector itself remains the same, this is a prime example of when a template is an excellent solution.
-Prelude