9

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} };
}

如上例所示,我必须提供 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 error generated.

任何解决方法或 C++17 之前的方法?

4

1 回答 1

2

您仍然可以提供构造函数,例如:

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>>;

演示

于 2019-04-09T19:09:47.330 回答