在派生 class 成员联合中包含继承基 class 成员

Include inherited base class member in derived class' member union

假设存在一个基数class如下:

class foo
{
    int x0;//private variable should not be a participant in derived union
           //(unless bar is a friend)
protected:
    int x1;
};

以及继承它的派生 class:

class bar : foo
{
protected:
    union
    {
        //int foo::x1;
        char[4] x2;
    };
};

我想将基础成员 x1 放入派生 class.

的成员联合中并重新使用它的 space

通常派生的 classes 可以与基础 class 成员一起玩,除了重新使用他们的 space.

之外可以做任何事情

问题

  1. 这是否可能使用任何 "magic" 并且仍然不受 UB 的影响?
  2. 如果不可能,有什么理由可以认为这是严重错误的吗?
  3. 是否有可能(如果有的话)将其扩展到联合内的无名结构以保存基本成员?

编辑: "magic",我不是指任何供应商特定的扩展。

你可以这样做:

class bar : foo
{
protected:
    char* x2() { return reinterpret_cast<char*>(&x1); }
};

这是允许的,因为严格别名对 char* 有例外。

我认为除此之外你无能为力(例如,如果你想使用 char* 以外的类型),除了重新排列 class 层次结构以将可联合部分从foo.

的非联合部分