"Sat" <> wrote in message
news:bp0cri$uuh$...
> I understand that the std::vector<DerivedElem*> is unrelated to
> std::vector<BaseElem*>. I am trying to see if anyone has a good idea of
> implementing this in a different way. The intent is to return a bunch of
> DerivedElem pointers in a container using a virtual function.
>
> I tried making GetAllElems a templated member function like this:
>
> template<ElemType>
> virtual void GetAllElems(std::vector<ElemType>& allElems) const;
>
> but later found that templated member functions cannot be virtual
functions.
That's right, probably because of implementation difficulties for the
compiler in constructing a v-table that can support templates.
> That's why I am stuck.
I can't think of any really nice way to do it. The best I can come up with
is a virtual function that takes a std::vector<BaseElem*> &, and a
non-virtual member function template in the base class that calls the
virtual function and converts the vector it creates into another vector of
the correct type of element using a cast. Or, if you want to ensure type
safety at the expense of execution time, you can dynamic_cast every element
separately.
Another, even nastier, method - but fast - would be to directly cast the
std::vector<DerivedElem*> & passed to the template member in the base class
into a std::vector<BaseElem*> & for passing to the virtual function.
I probably need a few slaps across the face from other regulars here or I
might come up with something even worse
DW