【问题标题】:How best to expose private inheritance to base class?如何最好地将私有继承暴露给基类?
【发布时间】: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&lt;Derived*&gt;(this)...谢谢。

标签: c++ inheritance multiple-inheritance private-inheritance


【解决方案1】:

你快到了。不要在Node 中存储对DERIVED_T 的引用。随便写:

     auto derivedThis& = *static_cast<DERIVED_T*>(this);

在每个需要它的功能中。 (或 const DERIVED_T* 视情况而定)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 2015-08-08
    • 2013-02-12
    • 1970-01-01
    • 2011-01-26
    • 2011-03-30
    • 2011-09-14
    相关资源
    最近更新 更多