Re: heterogenous container class
On Jan 12, 1:54 am, "A" <a...@a.a> wrote:
Can anyone give some clues how to restructure the above so it can be read
and written to similarly easy like the above but without the burden of
redundant constructors in each object e.g for TClassA to hold only "int i=
"
and not much else...
Any ideas are welcome.
I think that you need to think bigger about __operations__ your
TContainer should provide (currently it's a simple data storage). It
looks like you need some run-time polymorphism, but it's not clear
from uses you have shown. For example, in
if (Container[0].type == 0) int i = Container[0].ca;
if (Container[0].type == 1) float f = Container[0].cb;
What is really interesting is what happens with i and f later. You
should be able to extract services that TContainer should provide for
that "later" part. But that would require e.g.
std::vector<TContainer*> Container;
If you don't like that, you might use a wrapper that provides said
services, e.g.:
class TContainerHandler
{
public:
TContainerHandler(TClassBase& data) : FData(data) {}
virtual operation1() = 0;
virtual operation2() = 0;
protected:
TClassBase& FData;
};
// derive for TClassA and TClass B.
and then:
TContainerHandler& h = Container[0].type == 0 ?
TContainerHandlerA(Container[0]) : TContainerHandlerB(Container[0]);
// above needs some casting, perhaps doesn't work properly, either
Use(h);
Goran.