View Full Version : array + template ?

10th February 2006, 02:06

I work in a lemonade factory. We have data servers in our vats to tell us things like: pH level, sugar level, etc. Each vat has a separate data structure it passes to the data client GUI which I'm writing.

I have a bunch of pointers - one for each vat - to a lemonade template class, and I want to get them in an array or list somehow. The problem is that they are all different types.

Currently, they look like this:

LlcsLemonadeDataClient<YELLOW_LEM> *yellow_dc_p;
LlcsLemonadeDataClient<PINK_LEM> *pink_dc_p;
LlcsLemonadeDataClient<MELONADE> *melon_dc_p;

Is there any way I could do something like:
LlcsLemonadeDataClient <?> *lemonade_list[10];

My goal is to iterate through all the different lemonade data clients I have and set the pointers to NULL. And similar tasks. Currently I have to name every lemonade type in the factory and manually set the pointer to NULL:

yellow_dc_p = NULL;
pink_dc_p = NULL;

Any ideas? Is there an STL or Qt container approach?

10th February 2006, 09:25
Wrap those types into classes, like so:

struct common{


struct yellow : public common, YELLOW_LEM {


struct pink : public common, PINK_LEM {


struct melon : publik common, MELONADE {


And then:

std::list<common*> list;

Or simply:

union { YELLOW_LEM *yellow; PINK_LEM *pink; MELONADE *melon; } lemonades;
std::list<lemonades> list;

You'll have to cast to appropriate classes anyway, so both of this approaches are limited. You'd have to create your own set of classes and wrap each method of each of those pointers directly into a class, so that they share a common interface and have ability for run time type information.

10th February 2006, 19:02
Thanks again, Wysota.

Unfortunately it is as you say: a bit limited.

If I don't end up going with it, at least I learned a thing or two!


10th February 2006, 19:23
The thing you SHOULD do is to wrap all those classes (structs?) you get pointers to in real classes, sharing the common interface, for example:

struct Lemonade {
virtual string taste()=0;
virtual string colour()=0;

class YellowLemonade : public Lemonade {
YellowLemonade(YELLOW_LEM *l){ m_ptr = l;}
string taste(){ return m_ptr->taste(); } // common
string colour(){ return "yellow"; } // common
string yellowshade() { return m_ptr->shade(); } // yellow only
YELLOW_LEM *m_ptr;

class PinkLemonade : public Lemonade {
PinkLemonade(PINK_LEM *l){ m_ptr = l;}
string taste(){ return m_ptr->taste(); } // common
string colour(){ return "pink"; } // common
string pinkintensity(){ return m_ptr->intensity(); } // pink only
PINK_LEM *m_ptr;