相关疑难解决方法(0)

在空基类中使用聚合初始化时如何避免{}

C ++ 17对基类的聚合初始化很棒,但是当基数仅用于提供某些功能(因此没有数据成员)时,它很冗长。

这是最小的示例:

#include <cstddef>
struct base_pod
{
    // functions like friend compare operator
};
template<typename T, std::size_t N>
struct der_pod : public base_pod
{
    T k[N];
};

int main()
{
    der_pod<int, 2> dp {{}, {3, 3} };
}
Run Code Online (Sandbox Code Playgroud)

如上面的示例所示,我必须提供empty {},否则将发生编译错误。现场演示。如果我忽略它:

prog.cc:15:28: error: initializer for aggregate with no elements requires explicit braces
        der_pod<int, 2> dp{3, 3};
                           ^
prog.cc:15:31: warning: suggest braces around initialization of subobject [-Wmissing-braces]
        der_pod<int, 2> dp{3, 3};
                              ^
                              {}
1 warning and 1 …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance aggregate-initialization

7
推荐指数
1
解决办法
128
查看次数