c – 使用相同的构造函数参数初始化所有元素或std :: array
发布时间:2020-12-16 09:20:18 所属栏目:百科 来源:网络整理
导读:我想知道是否可以使用隐式删除的默认构造函数初始化std ::对象数组,而不知道数组大小的先验,因为它是模板参数,因此失去了使用初始化列表的可能性.代码如下,它打破了“调用隐式删除的std :: array的默认构造函数 A,3UL” struct A { A (int b,int c) : mb(b),
我想知道是否可以使用隐式删除的默认构造函数初始化std ::对象数组,而不知道数组大小的先验,因为它是模板参数,因此失去了使用初始化列表的可能性.代码如下,它打破了“调用隐式删除的std :: array的默认构造函数< A,3UL>”
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,1> { template<typename... Ts> static std::array<T,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; }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |