C++ 中的简单反钻石模式不可能吗?

问题描述 投票:0回答:1

我有四个类,具有以下强制转换(也称为构造函数)图:

    DataBase   ---->  DataDerived

        |                  |
        V                  V

    TableBase  ---->  TableDerived

每个表都有一个数据属性。

问题

现在,当

obj
TableDerived
类型时,那么:我如何使
obj.data::DataBase
obj.TableBase::data
是完全相同的实例? (即两个访问器是完全相同的单个物理引用)。

实施

这是我的实现:


struct DataBase{
    int i{};
};

struct DataDerived : DataBase{
    int j{};
    DataDerived(DataBase&& d):DataBase(std::move(d)){}
};

// above this line, everything is obvious. Below this line, things are unclear

struct TableBase{
    DataBase data; // may not live on Heap!!
};

struct TableDerived: TableBase{
    DataDerived data;
};

限制

我不希望表继承数据。我不想使用动态分配。我需要所有四个类在独立时是完整的(没有聚合,只有属性)。

我尝试了什么

GPT-4 提出的最佳解决方案是使用共享指针。这需要动态分配,这是不可取的。

我知道虚拟继承。但据我所知,这需要表继承数据,就我认为继承的含义而言,这对我来说似乎是不可取的。

c++ inheritance
1个回答
0
投票

问题在于,根据

TableBase
是单独实例化还是作为
TableDerived
的基础实例化,您想要的
data
成员具有不同的类型:在第一种情况下,它必须是
DataBase
并且在第二个
DataDerived
.

但是,像 C++ 这样的静态语言不支持这一点。

所以简单的答案是,这是不可能的。

© www.soinside.com 2019 - 2024. All rights reserved.