A
A
I'd like to create a heterogenous container class of various objects.
I would use std::vector for holding such objects.
Let's assume we have ClassA, ClassB objects
struct TClassA
{
int i;
TClassA() : i(0) {} // default init
TClassA(int ii) : i(ii) {} // init with value
}
struct TClassB
{
float f;
TClassB() : f(0.0) {} // default init
TClassB(float ff) : f(ff) {} // init with value
}
struct TContainer
{
TClassA ca; // holds a
TClassB cb; // holds b
int type; // what is stored, a or b
TContainer(TClassA ainit) : ca(ainit), type(0) {} // init for a
TContainer(TClassB binit) : cb(binit), type(1) {} // init for b
}
// Using the above
std::vector<TContainer> Container;
Container.push_back(TClassA(123)); // Add integer
Container.push_back(TClassB(123.456)); // Add float
//read
if (Container[0].type == 0) int i = Container[0].ca;
if (Container[0].type == 1) float f = Container[0].cb;
The above works but for larger structures it leaves unnecessary memory
footprint because each class holds init functions and container also holds
all of the redundant data.
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 would use std::vector for holding such objects.
Let's assume we have ClassA, ClassB objects
struct TClassA
{
int i;
TClassA() : i(0) {} // default init
TClassA(int ii) : i(ii) {} // init with value
}
struct TClassB
{
float f;
TClassB() : f(0.0) {} // default init
TClassB(float ff) : f(ff) {} // init with value
}
struct TContainer
{
TClassA ca; // holds a
TClassB cb; // holds b
int type; // what is stored, a or b
TContainer(TClassA ainit) : ca(ainit), type(0) {} // init for a
TContainer(TClassB binit) : cb(binit), type(1) {} // init for b
}
// Using the above
std::vector<TContainer> Container;
Container.push_back(TClassA(123)); // Add integer
Container.push_back(TClassB(123.456)); // Add float
//read
if (Container[0].type == 0) int i = Container[0].ca;
if (Container[0].type == 1) float f = Container[0].cb;
The above works but for larger structures it leaves unnecessary memory
footprint because each class holds init functions and container also holds
all of the redundant data.
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.