【发布时间】:2019-08-30 17:27:26
【问题描述】:
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} };
}
如上例所示,我必须提供空的{},否则会出现编译错误。 live demo。如果我省略它:
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 error generated.
任何解决方法或 C++17 之前的方法?
【问题讨论】:
-
我会注意到在您的示例中与基类没有任何关系,您可以删除它并查看错误仍然存在godbolt.org/z/0FpuQ5
-
@DmitryGordon 我需要这个基类。我提供的案例只是一个小例子
-
Pre C++17 你不能有基类,所以这不是问题。您只需将类及其所有运算符放在命名空间中即可。
-
你到底使用基类做什么?必须在派生类中重写比较函数才能使其工作。
-
关于您显示的错误,与例如相同。
std::array:对象本身需要一对外部大括号,然后是聚合数据的内部对。如der_pod<int, 2> dp{{3, 3}};。但这不起作用,因为继承和初始化基类的需要也是如此(导致初始为空{})。
标签: c++ inheritance aggregate-initialization