c – 根据模板参数生成不同大小的初始化列表
发布时间:2020-12-16 09:20:59 所属栏目:百科 来源:网络整理
导读:我有一个包含没有默认构造函数的对象数组T的类.这是一个例子: #include iostreamstruct Param { int x;};struct A { A(const Param p) { std::cout p.x std::endl; }};templateclass T,int nstruct Array { T data[n]; /* n times */ Array(const Param p)
我有一个包含没有默认构造函数的对象数组T的类.这是一个例子:
#include <iostream> struct Param { int x; }; struct A { A(const Param &p) { std::cout << p.x << std::endl; } }; template<class T,int n> struct Array { T data[n]; /* n times */ Array(const Param &p) : data{/* T(p),...,T(p) */} { } }; int main() { Param p{42}; Array<A,3> arr(p); return 0; } 我正在寻找一种方法,使用包含正好n个元素的元素T(p)的不同大小的初始化列表来初始化数据字段.我有一种感觉,它可以通过像std :: make_index_sequence这样的构造来实现,但我找不到合适的东西. 解决方法
我想你可以使用委托构造函数,std :: index_sequence和std :: make_index_sequence以及重写数组如下(编辑:回答由SergeyA和Rakete1111改进;谢谢!)
template <typename T,std::size_t N> struct Array { T data[N]; template <std::size_t ... Is> Array (Param const & p,std::index_sequence<Is...> const &) : data { ((void)Is,T{p}) ... } { } Array(const Param &p) : Array{p,std::make_index_sequence<N>{}} { } }; 也许你可以私有新的构造函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |