我想知道是否可以使用隐式删除的默认构造函数初始化std ::对象数组,而不知道数组大小的先验,因为它是模板参数,因此失去了使用初始化列表的可能性.代码如下,它打破了“调用隐式删
struct A {
A (int b, int c) : mb(b), mc(c) { }
int mb;
int mc;
};
template <size_t NR_A>
struct B {
B (int b, int c) :
// <- how to initialize mAs here?
{ }
std::array<A, NR_A> mAs;
};
B<3> inst(1,1);
编辑:我想将所有A的mAs初始化为A {1,1}
对于C 11和C 14(即:前C 17),您可以通过模板元编程实现您想要的.您可以声明以下帮助程序类模板array_maker<>,它具有静态成员函数模板make_array,它以递归方式调用自身:
template<typename T, std::size_t N, std::size_t Idx = N>
struct array_maker {
template<typename... Ts>
static std::array<T, N> make_array(const T& v, Ts...tail) {
return array_maker<T, N, Idx-1>::make_array(v, v, tail...);
}
};
然后,将此类模板专门用于Idx等于1的情况,即:递归的基本情况:
template<typename T, std::size_t N>
struct array_maker<T, N, 1> {
template<typename... Ts>
static std::array<T, N> make_array(const T& v, Ts... tail) {
return std::array<T, N>{v, tail...};
}
};
最后,它可以通过这种方式在模板的构造函数中使用:
template <size_t NR_A>
struct B {
B (int b, int c) : mAs{array_maker<A, NR_A>::make_array(A{b,c})}
{}
std::array<A, NR_A> mAs;
};
