>>i have defined a stack class using single linked list and a template. as follow:
template <class T>
class genStack{
public:
void push(T a){.....}
T pop(){........}
....
....
private:
SLList<T>: lst;
}

i know when i want the stack to store int, i should declare a stack like this:
genStack<int> gs;


but i want to store defferent types (double,char...) of data in the same stack, how can i do that?

If you want to store mixed data than I'd use a structure that has two members: (1) a union between all the data types you want it to support, and (2) an int that indicates what kind of data is stored, such as 0 no valid data, 1 is an short, 2 is an unsigned short, 3 is a int, 4 is an unsigned int, etc. etc.

struct dtype
{
   int type;
   union data
   {
        short sVal;
        unsigned short usVal;
        int iVal;
        unsigned int uiVal;
        long lVal;
        unsigned long ulVal;
        // etc for all other data types
   };
};

now just use that structure (or class if you like)

genStack<dtype> lst;

If you want to store mixed data than I'd use a structure that has two members: (1) a union between all the data types you want it to support, and (2) an int that indicates what kind of data is stored, such as 0 no valid data, 1 is an short, 2 is an unsigned short, 3 is a int, 4 is an unsigned int, etc. etc.

... keeping in mind that you have a problem if you want to add strings too. Think very carefully if you need them.

>>after "genStack<dtype> gs;"
like : i want to push an intger, do i just write:
"gs.push(7);" ???
then why it said "can not convert int to dtype"and "type mismatch in parameter 'el' in call to genStack<dtype>::push(const dtype &)"?

sorry for stupid qestions.

... keeping in mind that you have a problem if you want to add strings too. Think very carefully if you need them.

Not a problem -- just add the string to that. It might require some special handling. Microsoft has implemented identical thing in its VARIANT structure which is used all the time in COM programming, VB and VC++ compilers.

>>after "genStack<dtype> gs;"
like : i want to push an intger, do i just write:
"gs.push(7);" ???
then why it said "can not convert int to dtype"and "type mismatch in parameter 'el' in call to genStack<dtype>::push(const dtype &)"?

sorry for stupid qestions.

No you can't just do that. You have to first create a dtype object then push that object onto the stack

const int sType = 1; // short integer
const int usType = 2; // unsigned short
const int iType = 3; // integer
// etc. etc
genStack<dtype> lst;
...
...
dtype d;
d.type = iType; // we want an integer
d.iVal = 7; // set the integer value
lst.push(d); // put on stack
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.