I have a base structure FooBase:
struct FooBase { };
Then I create a template structure Foo which is a child of FooBase:
template <typename typeName> struct Foo : public FooBase { typeName* foo };
In some class I create a vector of FooBase and add instances of Foo in it:
vector <FooBase> FooVector
...
Foo <Bar> fooInstance;
fooInstance.foo = new Bar();
FooVector.push_back ( fooInstance );
Then I needed to access the stored data, but I’m getting predictable and obvious error about an absence of the member foo in FooBase
FooVector[0].foo
I can not write something like
Foo <Bar> fooInstance = FooVector[0]
since I don’t know the template parameter.
How do I store instances of Foo in the vector so I can access them later. Note, that I don’t know the template parameter at the last step – when reading data from the vector.
P.S. NO BOOST ALLOWED!
What happens here, is that in your
line, C++ silently invokes the copy constructor of
FooBase, because you can only keep objects of that type in your vector. SinceFooinherits publicly fromFooBasethe methodFooBase::FooBase(FooBase const&)can be called with an object of typeFoo.So, you’re not really storing
Foos, but in factFooBases. To do what you want to do you need anstd::vector<FooBase*>orstd::vector<std::shared_ptr<FooBase> >.However, the contents of your vector, will still lack a
foomember, because the static type is still notFoo. To get around this, you have some options. You coulddynamic_castorstatic_castyourFooBase*into aFoo*and then access itsfoomember. But that could break, since theFooBase*pointers might actually hold another type thanFoo.Why don’t you just use an
std::vector<Foo<Bar> >instead?