在C++ 11中私有地继承聚合类的类的聚合初始化

rob*_*jam 1 c++ inheritance aggregate-initialization c++11

请考虑以下代码:

struct base
{
    int x, y, z;
};

struct derived : private base
{
    using base::base;
};

int main(int argc, const char *argv[])
{
    base b{1, 2, 3}; // Allowed
    derived d{1, 2, 3}; // Not allowed
}
Run Code Online (Sandbox Code Playgroud)

derived d{1, 2, 3};行使我的编译器(Clang 3.3)失败,错误"没有匹配的构造函数用于初始化'derived'".为什么是这样?有没有办法derived通过聚合初始化初始化?

Jer*_*fin 9

derived 有一个基类,所以它不是一个聚合(§8.5.1/ 1:"聚合是一个数组或类(第9条),没有基类[...]").

由于它不是聚合,因此无法使用聚合初始化进行初始化.

最明显的解决方法可能是添加一个ctor到base,并让ctor derived传递参数到base:

struct base
{
    int x, y, z;

    base(int x, int y, int z) : x(x), y(y), z(z) {}
};

struct derived : private base
{
    derived(int a, int b, int c) : base(a, b, c) {}
};

int main(int argc, const char *argv[])
{
    base b{1, 2, 3}; // Allowed
    derived d{1, 2, 3}; // Allowed
}
Run Code Online (Sandbox Code Playgroud)

当然,如果您设置base剩余聚合,那么这不起作用.

编辑:对于编辑过的问题,我没有看到在std::initializer_list这里使用的方法- std::array没有任何东西可以接受initializer_list.