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之前的版本吗?
答案 0 :(得分:1)
您仍然可以提供构造函数,例如:
template <typename T, std::size_t N> using always_t = T;
struct base_pod
{
// functions like friend compare operator
};
template<typename T, typename Seq> struct der_pod_impl;
template<typename T, std::size_t ... Is>
struct der_pod_impl<T, std::index_sequence<Is...>> : base_pod
{
der_pod_impl(always_t<T, Is>... args) : k{args...} {}
T k[sizeof...(Is)];
};
template<typename T, std::size_t N>
using der_pod = der_pod_impl<T, std::make_index_sequence<N>>;