我正在设计一个对象层次结构,其中所有对象的基类都是Node
,预计将被子类化。的子类Node
将包含子项,但子项的类型可能因子类而异。
我通过从Owner<>
类中私有继承来实现子项的所有权,这只是std::vector
. 我想将此所有权公开给基类(但没有其他人),因为在添加和删除子项方面有很多重复。所以我想出了这个:
#include <vector>
using namespace std;
//Class to contain child items
template <typename T>
struct Owner {
vector<T> children;
};
//Types of children that can be owned by nodes in the hierarchy
struct ChildType1{};
struct ChildType2{};
struct ChildType3{};
//Node base class
template <typename DERIVED_T>
struct Node {
Node(DERIVED_T& _derivedThis):
derivedThis(_derivedThis)
{}
template <typename ITEM_T>
void AddItem() {
/*Possibly do a lot of pre-checks here before adding a child*/
derivedThis.Owner<ITEM_T>::children.emplace_back();
}
//Reference to the most-derived subclass instance
DERIVED_T& derivedThis;
};
//A possible subclass of Node
struct DerivedNode:
private Owner<ChildType1>,
private Owner<ChildType2>,
public Node<DerivedNode>
{
friend struct Node<DerivedNode>;
DerivedNode():
Node(*this)
{}
};
int main() {
DerivedNode d;
d.AddItem<ChildType1>();
d.AddItem<ChildType2>();
//d.AddItem<ChildType3>(); //Fails to compile (intended behavior; DerivedNode should not own ChildType3 objects)
return 0;
}
这种方法感觉有点混乱,因为我在基类中存储了对派生类的引用(我以前从未见过)。这是好习惯吗?在处理基类中的通用子维护时,是否有更好的方法来保持派生类中的子所有权?