使用空基 class 的聚合初始化时如何避免 {}
How to avoid {} when using aggregate initialization with empty base class
C++17 对基 class 的聚合初始化非常棒,但是当基仅用于提供一些功能(因此没有数据成员)时,它会很冗长。
这里是最小的例子:
#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 之前的方法?
您仍然可以提供构造函数,例如:
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>>;
C++17 对基 class 的聚合初始化非常棒,但是当基仅用于提供一些功能(因此没有数据成员)时,它会很冗长。
这里是最小的例子:
#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 之前的方法?
您仍然可以提供构造函数,例如:
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>>;