+ 3
Can someone explain how to use templates and what their for in C++?
I am passing this in the C++ Course right now. Can anyone post some examples of them and also explain how I can use them in C++ programming. //Huge Thanks!!!!đ
2 Answers
+ 4
Templates allow you use declare functions that can work with any data type by declaring a temporary class or typename and then substituting it with the type of the arguments passed during compilation.
Eg :
Consider this function:
int max(int a, int b)
{
if(a>b) return a;
return b;
}
main()
{
cout<<max(2,3)<<endl; //Prints 3.
}
But as you can see, you cant use the same function for a string or a custom class, like some Complex Numbers class, or for arrays.
So, the only way one could think would be to overload the function seperately for the different types that we need. But that is tedious to do.
So, C++ introduced templates, which can be used instead to declare the function for all types at the same time just once .
So now you do:
template<typename T>
T max(T a, T b)
{
if(a>b) return a;
return b;
}
T is a temporary class that you use to create variables that can store variables of any data type.
Thus, you pass T, so that the function can work with ints, chars, floats, strings, classes, etc.
Now, you can use this like this:
main()
{
cout<<max(2,3)<<endl;
cout<<max('2','a')<<endl;
cout<<max("hello","world");
cout<<max(complex(2,3),complex(3,4));
}
Note that this will not work with types that do not have the > operator overloaded for them. Thus, don't use this max function with char*.