is it possible to have a generic stack which works for all the primitive and non primitive data types????

Sir this is very serious question because this is confusing me a lot look at the code of push method of the integer stack

void Stack::push(int number)
{
Node* newNode=new Node;
if(head==NULL)
{
head=newNode;
topelement=newNode;
current=newNode;
head->object=number;
head->preptr=NULL;
}
else
{
topelement=newNode;
newNode->preptr=current;
current=topelement;
newNode->object=number;
}
}

Now my question is if we make it generic using templates then it can work very well for integers , floats , long , double etc , but what about strings?
For example I have an array in my main program in which I get the string from the user and after that I pass this array to the push method of the stack, now look at the code of push method written for strings only.

void stack::push(char* ptr)
{
if(ptr==NULL)
{
cout<<"\n Can't be pushed";
return;
}
Node* newNode=new Node;
if(top==NULL)
{
head=newNode;
current=top=newNode;
head->preptr=NULL;
//allocating space for the passed string
int len;
len=strlen(ptr);
head->data=new char[len+1];
strcpy(head->data,ptr);
head->data[len]='\0';
}
else
{
top=newNode;
newNode->preptr=current;
current=newNode;
int len;
len=strlen(ptr);
newNode->data=new char[len+1];
strcpy(newNode->data,ptr);
newNode->data[len]='\0';
}
}

You are required to make this method generic so that it works for all the primitive data types , strings and the user defined objects. How would you do that ?

>How would you do that ?
Look up template specialization. You write a generic template that handles the majority of types, then specialize on the ones that don't support the same operations. In your example, the template for C-style strings would be a specialization because C-style strings have different semantics for dynamic allocation and copying.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.