Click here to Skip to main content
16,018,525 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is it possible to have a generic stack which works for all the primitive and non primitive data types?

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

C++
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.

C++
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';
    }
}


I am required to make this method generic so that it works for all the primitive data types, strings and the user defined objects. How would I do that?
Posted
Updated 19-Dec-09 22:28pm
v3

I would make Node into a template class, so that Data is type T. Then you can simply use Node<int>, Node<char *> and whatever else floats your boat. Then, simply make stack into a template class, changing the ptr parameter to be of type T. From here, you simply set newNode->data to ptr, or a copy thereof.
 
Share this answer
 
You may use std::string instead of char *.
BTW Do you know C++ standard library privides a stack template class?
:)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900