如何初始化 std::array<T, n>如果 T 不是默认可构造的,那么优雅吗?

2022-01-18 00:00:00 arrays initialization templates c++ c++11

我如何初始化 std::array<T, n> 如果 T 不是默认可构造的?

我知道可以这样初始化它:

T t{args};std::array<T, 5>一个{t,t,t,t,t};

n 对我来说是模板参数:

template无效 f(T 值){std::array<T,N>项目 = ???}

而且即使它不是模板,如果 n 太大,手动重复值也是相当难看的.

解决方案

给定 N,你可以生成一个名为seq<0,1,2,3,...N-1>的序列类型

code> 使用名为 genseq_t<> 的生成器,然后执行以下操作:

template无效 f(T 值){//genseq_t<N>是seq<0,1,...N-1>std::array<T,N>项目=重复(值,genseq_t<N>{});}

其中repeat定义为:

template自动重复(T 值,seq)->std::array<T, sizeof...(N)>{//解压 N,重复 `value` sizeof...(N) 次//注意 (X, value) 的计算结果为 value返回 {(N, 值)...};}

其余的定义为:

模板结构序列{使用 type = seq;静态常量 std::size_t 大小 = sizeof ... (N);模板<int I>struct push_back : seq<N..., I>{};};模板<int N>结构 genseq : genseq<N-1>::type::template push_back<N-1>{};模板<>结构 genseq<0>: seq<>{};模板<int N>使用 genseq_t = typename genseq<N>::type;

在线演示

希望对您有所帮助.

How do I initialize std::array<T, n> if T is not default constructible?

I know it's possible to initialize it like that:

T t{args};
std::array<T, 5> a{t, t, t, t, t};

But n for me is template parameter:

template<typename T, int N>
void f(T value)
{
    std::array<T, N> items = ??? 
}

And even if it wasn't template, it's quite ugly to repeat value by hand if n is too large.

解决方案

Given N, you could generate a sequence-type calledseq<0,1,2,3,...N-1> using a generator called genseq_t<>, then do this:

template<typename T, int N>
void f(T value)
{
     //genseq_t<N> is seq<0,1,...N-1>
     std::array<T, N> items = repeat(value, genseq_t<N>{});
}

where repeat is defined as:

template<typename T, int...N>
auto repeat(T value, seq<N...>) -> std::array<T, sizeof...(N)> 
{
   //unpack N, repeating `value` sizeof...(N) times
   //note that (X, value) evaluates to value
   return {(N, value)...}; 
}

And the rest is defined as:

template<int ... N>
struct seq
{
   using type = seq<N...>;

   static const std::size_t size = sizeof ... (N);

   template<int I>
   struct push_back : seq<N..., I> {};
};

template<int N>
struct genseq : genseq<N-1>::type::template push_back<N-1> {};

template<>
struct genseq<0> : seq<> {};

template<int N>
using genseq_t = typename genseq<N>::type;

Online demo

Hope that helps.

相关文章