在空基类中使用聚合初始化时如何避免{} [英] How to avoid {} when using aggregate initialization with empty base class
本文介绍了在空基类中使用聚合初始化时如何避免{}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C ++ 17对基类的聚合初始化非常棒,但是当基类仅在其中提供某些功能(因此没有数据成员)时,它很冗长.
C++17's aggregate initialization for base class is awesome, but it is verbose when the base is only there to provide some functions (so no data members).
这里是最小的例子:
#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} };
}
如上面的示例所示,我必须提供空的{}
,否则将发生编译错误. 实时演示.如果我忽略它:
As the example above shows, I have to provide empty {}
, otherwise compile error will occur. live demo. If I omit it:
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之前的版本吗?
Any workaround or pre-C++17 way?
推荐答案
您仍然可以提供构造函数,例如:
You can still provide constructor, for example:
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>>;
这篇关于在空基类中使用聚合初始化时如何避免{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文