"alg" <al******@yahoo.com> wrote in message
news:gI*********************@bgtnsc04-news.ops.worldnet.att.net...
Is it possible to put different types of objects in a single STL list? If
not what STL template should be used which will contains various objects
of different types?
Thanks for your help!
This question does get asked often enough, and I always ask myself why? Why
do you need to store objects of different types and how do you plan to work
with them?
Suppose we do have a magical container that can store objects of different
types.
************************************************** *
A a;
B b;
C c;
MagicContainer list;
list.insert(a);
list.insert(b);
list.insert(c);
************************************************** *
all fair so far. Now how do we get stuff out of the list?
A *a = list.front(); ?
How do we know the element is of type A? Maybe its of type B, or C?
You see the issue?
So now you can either create the list as a (void*) list and magically know
what to cast the elements back to.
You could create some kind of container structure that includes the type.
struct
{
int myType;
void *data
}
You could create a union with an explicit type
struct
{
int myType;
union
{
A a;
B b;
C c;
}
}
You could do it the C++ way and create a common base class, make the list of
that type. Make all common operations virtual and away you go, its a
beautiful thing. If you want to get messy a bit and mix C/C++, include a
myType variable as part of the base class, and have each derived class set
that variable to its own thing. Then if you really need to, you know what
to cast it to using dynamic_cast.
Yamin