【发布时间】:2016-04-20 01:34:07
【问题描述】:
我正在设计一个对象层次结构,其中所有对象的基类都是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;
}
这种方法感觉有点混乱,因为我在基类中存储了对派生类的引用(我以前从未见过这种情况)。这是好习惯吗?在处理基类中的通用子级维护时,是否有更好的方法来保持派生类中的子级所有权?
【问题讨论】:
-
你读过CRTP吗?
-
我想我只阅读了维基百科的第一段。我从未想过使用
static_cast<Derived*>(this)...谢谢。
标签: c++ inheritance multiple-inheritance private-inheritance