我有組件:
struct ComponentStorage : Storage{
...
};
template<typename T = ComponentStorage>
class Component{
public:
T* storage;
...
}
有以下形式的派生類:
struct Component2Storage : Storage{
...
};
template<typename T = Component2Storage>
class Component2 : public Component<T>{...}
組件和存盤都有多個繼承級別。
我的問題與將組件作為輸入的函式有關,例如:
void myFunction(unordered_set<Component*> components){...} // This won't compile
如何修改我的函式,以便我可以傳遞一個包含不同型別組件的集合,這些組件可能使用不同型別的存盤?實際功能不會區別對待不同型別的組件。
uj5u.com熱心網友回復:
如果需要在同一個容器中存盤不同的組件,就需要多型。
所以你需要你Component的 s 有一個共同的基類,以便能夠這樣對待它們。
struct ComponentStorage : Storage{
...
};
class ComponentBase {
// ... define your common interface
}
template<typename T = ComponentStorage>
class Component : public ComponentBase{
public:
T* storage;
...
}
現在您可以將所有組件視為ComponentBase*并通過定義的通用介面處理它們。
std::variant<...all the component types>將or存盤std::any在集合中也可能是一種選擇,但它具有自己的優缺點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438732.html
