What's template?
You have probably seen me using it in some classes that I posted earlier, for instance Stack Class. So what is the purpose of template? Well, templates allow us to use a class or object for different datatypes using type casting. For instance, the Stack class I made earlier can be used for char, int, double, float, string or any other class/object.
For instance, I can use it for Int
myStack <int> stackOne;
Or for Char
myStack <char> stackTwo;
Or for String
myStack <string> stackThree;
Or maybe for a struct
struct Student{
string RollNum;
string Name;
float cgpa;
}
myStack <Student> stackFour;
In some way, it allows my Stack class to become universal.. or I should say not strictly limited to any data type.
How to use Template?
template <typename T>
This is the syntax to declare it. You can use any name in place of that T that I have used e.g.
template <typename myType>
If you are going to use it in any function or method, just declare it above that method. If there are several methods 一 I am not talking about functions within a class 一 declare it above each method.
For example,
template <typename A>
A Sum(A variable1, A variable2) //Note that I have used A in place of datatype in return type and variables
{
A answer = variable1 + variable2;
return answer;
}
Now if you have another function below it, you will have to declare it again above that function.
Similarly, if you want it in a struct, you will declare it above that struct.
Same goes for the class, if you use it in a class, declare it above the class however the point to remember is that you will then not need to declare it again and again for each function in the class rather once declared outside is enough.
template <typename T>
class myStack
{
Vector <T> st;
public:
T top()
{
int s = st.getSize() - 1;
T ret = st[s];
return ret;
}
T getAt(int i)
{
return st[i];
}
}
That'll be all for today. Thank you for reading! ^^
0 comments:
Post a Comment