1 year ago
#377937
WalleyM
Dealing with Template Covariance without Dynamic_Cast or Templated classes
I am trying to create a class structure that works like this:
class Base
{
public:
class NestedBase
{
};
virtual std::vector<NestedBase*> getNested();
};
class Derived : public Base
{
public:
class NestedDerived : public Base::NestedBase
{
};
std::vector<NestedDerived*> getNested() override;
};
Where I can access the specific NestedDerived* list through an instance of Derived.
I understand why this will not work from the following posts: 1, 2.
The main alternative strategy described is to continue to use the NestedBase* vector and use dynamic_cast on every instance when using the derived class.
This solution seems messy and problematic to me since it relies on the client knowing which type the nested instances must be cast to.
Another solution which was presented was to make base into a class template that takes the NestedClass. I cannot use this since I need to use base instances without knowing their derived type.
Is there a solution available which allows me to get the specific nested list from derived classes but also allows me to get the base nested list from the base class.
In response to the comments asking for more detail: I want to use the nested class polymorphically. But I also want to use it as a specific type. The derived nested type has the common features of the base nested type with some extended functionality on top.
While dealing with the nested list in the base class, a const getter could be used which would stop other types being added, if that helps at all?
c++
oop
templates
covariance
0 Answers
Your Answer