C++17 之前的聚合初始化

Aggregate initialization pre-C++17

考虑以下 class 由聚合构成的层次结构:

struct Foo {
    int k;
    double d;
};

struct Bar : Foo {
    int i;
};

现在,假设我想从 Foo 类型的对象初始化 Bar 类型的对象,为 i 提供额外的参数。 (由于这里讨论的乏味,向 Bar 添加一个构造函数,它接受 Fooint,或者修改 BarFoo 在任何其他方式是不可能的)。在 C++17 中,我会使用聚合初始化:

auto make(const Foo& f) {
    return Bar{f, 42};
}

这在 C++14 中不可用。还有什么我可以做的来模仿 C++14 中所需的行为吗?我试图避免像

这样的事情
auto make(const Foo& f) {
    Bar b;
    b.k = f.k;
    b.d = f.d;
    b.i = 42;
    return b; // or return Bar{f.k, f.d, 42};
}

我试图避免的事情是让 make 了解 Foo 的内部结构 - 即 make 知道如何初始化 [=14= 的额外成员是很好的],但不希望初始化 Bar 的成员,这些成员与 Foo.

相同
auto make(const Foo& f) {
  Bar b;
  static_cast<Foo&>(b) = f;
  b.i = 42;
  return b;
}