I have components:
struct ComponentStorage : Storage{
...
};
template<typename T = ComponentStorage>
class Component{
public:
T* storage;
...
}
There are derived classes of the form:
struct Component2Storage : Storage{
...
};
template<typename T = Component2Storage>
class Component2 : public Component<T>{...}
There are multiple levels of inheritance both for Component and for Storage.
My question has to do with functions that with take a Component as input, for example:
void myFunction(unordered_set<Component*> components){...} // This won't compile
How do I modify my function so I can pass a set containing different kinds of components which may be using different kinds of storage? The actual function doesn't treat different kinds of components differently.
CodePudding user response:
If you need to store different components in the same container, you need polymorphism.
So you need your Component
s to have a common base class, to be able to treat them as such.
struct ComponentStorage : Storage{
...
};
class ComponentBase {
// ... define your common interface
}
template<typename T = ComponentStorage>
class Component : public ComponentBase{
public:
T* storage;
...
}
Now you could treat all components as ComponentBase*
and handle them through the common interface defined.
Storing a std::variant<...all the component types>
or std::any
in the set could also be an option, but it comes with it's own set of pros and cons.