Tuesday, July 24, 2018

c++ - How to use a single Template statement for more than one function or struct?



I've been trying to represent Stacks as a template, I used a struct and every thing is good, but every time I wanted to write a template function, I had to write the same template statement, which didn't seem correct -although working-



So how can I write one template statement for all the functions?, here is my code :





template
struct Stack
{
T Value;
Stack* next;
};
template
void Push(T Value,Stack* &Top)

{
Stack * Cell = new Stack();
Cell->Value = Value;
Cell->next = Top;
Top = Cell;
};
template
bool IsEmpty(Stack * Top)
{
return (Top==0);

}
template
void Pop(T &Value,Stack* &Top)
{
if (IsEmpty(Top))
cout * Temp = Top;
Value = Top->Value;
Top = Top->next;
delete Temp;
}

}
template
void GetTop(T &Value, Stack* &Top)
{
if (IsEmpty(Top))
cout Value;
}
template
void EmptyStack(Stack * &Top)
{

Stack * Temp;
while (!(IsEmpty(Top)))
{
Temp = Top;
Top = Top->next;
delete Temp;
}
}



Hope what I mean is clear now, sorry for the slight question :(



thanks in advance.


Answer



If (as appears to be the case based on your comment) you want them as free functions, you can't. You'll also have to change the Stack parameter, something like this:



template 
void Push(T Value, Stack* &Top)
{
Stack * Cell = new Stack();

Cell->Value = Value;
Cell->next = Top;
Top = Cell;
};


As it stands, I'm not too excited about your design though. You try to use the Stack type as both an actual stack, and as a single node (Cell) in the stack. This is unnecessarily confusing at best.



Edit: As far as stack vs. node goes, what I'm talking about is (as in the code immediately above): Stack *Cell = new Stack(); -- you're allocating a single Cell that goes in the stack, but the type you're using for it is Stack.




I'd do something like this instead:



template 
struct Stack {
struct node {
T data;
node *next;
};

node *head;

};

template
void push(T item, Stack *&s) {
Stack::node *n = new Stack:node();
n->data = item;
n->next = s->head;
s->head = n;
}



It doesn't make a lot of difference in what you're really doing, but when you're putting something onto a stack, allocating a Stack::node seems (at least to me) to make a lot more sense than allocating a Stack. A stack containing multiple nodes makes sense -- a Stack containing multiple stacks really doesn't.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...